PHP - Create Array Using Sql Query Result Set
Hi,
I have attached sql script for table structure and sample data. When I run following sql query ,I get result set. Code: [Select] select * from tablename order by col10 desc I want to create array using result set. Following is the require structure of array. Code: [Select] <?php $resultSet[]=array ( ('0') =>array ( ('col10value1') => array ( ('0') => array ( ('col1') => 'col1', ('col2') => 'col2', ('col3') => 'col3', ('col4') => 'col4', ('col5') => 'col5', ('col6') => 'col6', ('col7') => 'col7', ('col8') => 'col8', ), ('1') => array ( ('col1') => 'col1', ('col2') => 'col2', ('col3') => 'col3', ('col4') => 'col4', ('col5') => 'col5', ('col6') => 'col6', ('col7') => 'col7', ('col8') => 'col8', ), ), ), ('1') => array ( ('col10value2') => array ( ('0') => array ( ('col1') => 'col1', ('col2') => 'col2', ('col3') => 'col3', ('col4') => 'col4', ('col5') => 'col5', ('col6') => 'col6', ('col7') => 'col7', ('col8') => 'col8', ), ), ), ); ?> Similar TutorialsHi All, I have a select statement $stmt = $conn -> prepare(' SELECT u.user_firstname, u.user_lastname, so.staff_id, r.role_name FROM ssm_staff_order so INNER JOIN ssm_user u on so.staff_id = u.user_id INNER JOIN ssm_role r on u.user_role_id = r.role_id WHERE job_id = ? '); $stmt -> bind_param('i', $jid); $stmt -> execute(); $stmt -> bind_result($fn, $ln, $id, $role); The result looks like this +----------------+---------------+----------+-----------+ | user_firstname | user_lastname | staff_id | role_name | +----------------+---------------+----------+-----------+ | FName | LName | 8 | Chef | | jon | smith | 15 | Manager | | Chelsea | Hockley | 2 | Manager | +----------------+---------------+----------+-----------+ I am wanting to build an array so that i can foreach the result with the people under the header of their role. I know this is not difficult but i am going around and around with it and clearly missing the key part. As always your help is appreciated. So my question is the following: i have a form where the user can search for multiple terms (green, red, black, orange etc) the terms are seperated by a coma when the form is submitted and then those terms are placed in an array. I then make for values matching those terms, using the following script: Code: [Select] //$tagArr = array(red, black); $makeQuery = mysql_query("SELECT * FROM points_tags WHERE tag_id IN('".implode("','", $tagArr)."')"); $num_results = mysql_num_rows($makeQuery); The table "point_tags" containts two columns one that has that holds a value id and the other holds the term, a value can have multiple terms so it looks kinda like this: tag_id term_id car red car black boat orange plane black You get the idea right? Anyway the current query is grabbing all values matching those terms in. However what i want to get done is grab the values that have those exact terms only, so in theory something similar to the following: Code: [Select] $makeQuery = mysql_query("SELECT * FROM points_tags WHERE tag_id="term1' AND tag_id='term2'"); Where if i search for red and black i only get car returned because car has both the terms red and black, while plane has black it does not contain the term red. Does that make sense? I've been trying to figuring this out myself for a while already and i just can't think of a way to do this. I hope someone here can help me out EDIT::: What i meant to accomplish with the second query example was that i need to accomplish that same type of task (or using OR ) but while keeping the values in an array, so again in theory that (tag_id='term1' AND tag_id='term2') would just keep incrementing based on the number of values i'm searching for, so if there is only one value been searched for then there would not be any "AND". The AND or OR would get added if there are more than one value. Make sense what i'm talking about? Hello all. I am using a premade login script which has some very powerful function built in, the one I am looking at using is as follows:
/** * query - Performs the given query on the database and * returns the result, which may be false, true or a * resource identifier. */ function query($query){ return mysqli_query( $this->connection, $query); }The issue is, displaying the results. I call is via the following code: $database->query('SELECT LastName, Firstname FROM Patrons WHERE LastName = "Delude"');But I have no idea how to display it. I have attempted to echo it out, but I get the following error in the logs: PHP Catchable fatal error: Object of class mysqli_result could not be converted to string Hi there
I am new to this forum and not much of a php expert. I hope you can assist me.
My problem is as follows:
I have a column consisting of several values (in this case: sceience, art, humanistics and music)
I would like to use the following mysqli query in order to count the appearances of each value in this column:
$query = "SELECT SUM (IF(department = 'science', 1, 0)) AS science, SUM(IF(department = 'art', 1, 0))-> AS art FROM new2"
I have tried lots of ways to loop the results but couldn't get the it working.
Can anyone suggest any idea?
Thanks
Hanan
Hi all !,
I am stuck on the following piece of code which does not give an error nor does it give a result. ( i.e. it gives 0 num_rows which should be > 1).
If, however, I execute the query in phpmyadmin by simply substituting the values of $pp,$ll and $room_no in the query it gives the correct result.
Please can someone tell me what I may be doing wrong here. Thanks !
$fcon = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection'); $pp = "(ms.level = 'Beginner' || ms.level = 'Intermediate')"; $ll = 'ms.diff <= 7'; $room_no = 4; $query = "SELECT md.Member_reg_id, md.fname, md.lname, md.email, md.cell, ms.level, ms.diff, ms.score, r.ID_Status FROM register as r JOIN member_detail as md ON r.ID = md.Member_reg_id JOIN memstatus as ms On r.ID = ms.ID WHERE r.CENTERCODE = ? AND r.ID_Status ='A' AND ? AND ? ORDER by level, diff, score DESC"; $stmt=$fcon->prepare($query); $stmt->bind_param('iss',$room_no,$pp,$ll); if(!$stmt->execute()) die('Failed to execute the query'.$fcon->error); else { echo "Executed"; $stmt->bind_result($Member_reg_id,$fname,$lname,$email,$cell,$level,$diff ,$score,$ID_Status); $numrows = $stmt->num_rows; $stmt->store_result(); // echo $numrows; while($stmt->fetch()) { echo "<br>".$fname.' '.$lname; echo "<br>".$level; echo "<br>".$diff; echo "<br>".$score; echo "<br>".$cell; echo "<br>".$email; } } Edited by ajoo, 03 January 2015 - 08:00 AM. Hi everyone. I have this code that suppose to divide the query result 3 columns in a row. Like this : Shoes Hats Jeans Shorts Shirts Belts But for some reason this one doesn't work. It gave me everything in a single row. Like this: Shoes Hats jeans Shorts Shirts Belts. I noticed that before I put this two 2 lines of code, it's working fine. It didn't give me any error messages or anythings. Can someone point me out what did I did wrong? This is two lines I put in: Code: [Select] $vuong_query = tep_db_query("select categories_id from " . TABLE_GENDER_CATEGORIES . " where parent_id = 1"); while ($product_check = tep_db_fetch_array($vuong_query)) { This is the whole piece of code: Code: [Select] <tr> <td><table width = "100%" border="1" bordercolor="maroon"> <tr> <?php $vuong_query = tep_db_query("select categories_id from " . TABLE_GENDER_CATEGORIES . " where parent_id = 1"); while ($product_check = tep_db_fetch_array($vuong_query)) { $categories_querys = tep_db_query("select c.categories_id, cd.categories_name, c.categories_image from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = '" . $product_check['categories_id'] . "' and c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' order by sort_order, cd.categories_name"); $number_of_categories = tep_db_num_rows($categories_querys); $rows = 0; while ($categories = tep_db_fetch_array($categories_querys)) { $rows++; $cPath_new = tep_get_path($categories['categories_id']); $width = (int)(100 / MAX_DISPLAY_CATEGORIES_PER_ROW) . '%'; echo ' <td align="center" class="smallText" width="' . $width . '" valign="top"><a href="' . tep_href_link(FILENAME_DEFAULT, $cPath_new) . '">' . tep_image(DIR_WS_IMAGES . $categories['categories_image'], $categories['categories_name'], SUBCATEGORY_IMAGE_WIDTH, SUBCATEGORY_IMAGE_HEIGHT) . '<br>' . $categories['categories_name'] . '</a></td>' . "\n"; if ((($rows / MAX_DISPLAY_CATEGORIES_PER_ROW) == floor($rows / MAX_DISPLAY_CATEGORIES_PER_ROW)) && ($rows != $number_of_categories)) { echo ' </tr>' . "\n"; echo ' <tr>' . "\n"; } } } ?> </tr> </table> </td> </tr> Thanks anyone for helping me out. Vanvoquan Hello, So I have a content management site set up, but I'm stuck on one part. I have a query. Code: [Select] Select `email` FROM author WHERE author.id IN(SELECT authorid FROM job WHERE id = '$_POST[id]') I'm a beginner in PHP and SQL. Basically I need the query to run, it will come out with one result and I need that to be where the email is sent to. This is the existing code I have for sending out the email $subject = " Job Application Confirmation"; $message = "Hello $_POST[name] , \r\rYou, or someone using your email address, has applied for the job: $text Using the Resource Locator at Prahan.com. Keep this as future reference. \r\r Full Name: $_POST[name] \r Location: $_POST[location] \r Email: $_POST[email] \r Additional Information: $_POST[info] \r Job ID: $id \r Job Name: $text \r \r Expect a response shortly. \r\r Regards, Prahan.com Team"; $headers = 'From: Prahan.com Team <noreply@prahan.com>'; 'Reply-To: noreply@prahan.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $to1 = 'pratik@prahan.com'; mail($to1, $result, $message, $headers); Thanks in Advance! hello I'm using this code: Code: [Select] $query="SELECT * FROM `second_content` WHERE CHANGED =0 limit 0,1";to query first row data when I want see it and echo it I recived : Code: [Select] Resource id #2can anyone help me ? thank you Hello, I am new to the board and PHP. I created a simple store locator app with PHP. It pulls the info from a database. I want to take the website field from the table, once it is returned from the query, and have it print out a a hyperlink. Please help. Thanks, I have posted most of the relevant code. <?php if (isset ($stores)) { if (!empty ($stores)) { echo '<p><strong>' . count ($stores) . ' results were found.</strong></p>'; foreach ($stores as $value) { echo '<p><strong>' . $value['name'] . '</strong><br />'; echo $value['address'] . '<br />'; echo $value['town'] . ', ' . $value['state'] . ' ' . $value['postal']; echo ' <a target="_blank" href="http://maps.google.com/maps?q=', $value['address'], ' ', $value['town'], ', ', $value['state'], ' ', $value['postal'],'">Map this location</a><br />'; echo 'Phone: ' . $value['phone'] . '<br />'; echo 'Website: ' . $value['website'] . '<br />'; echo 'Email: ' . $value['email'] . '<br />'; echo 'Hours: ' . $value['hours'] ; echo '</p>'; } } else { echo '<p><strong>No results found</strong></p>'; } } ?> Hello. This one is driving me up the wall. It used to work, I have a sports league database (MsSql) and one of the tables contains team Captain's first name, last name, etc.. To create a unique but simple login, the query searches for the captain's first initial of their first name + lastname + league. However since there is the remote possibility of two similar usernames (i.e. David Smith) if the last name is found, the query adds an integer to the end of the last name. So the result would look like this: DSmithM4A At the moment, my database is completely blank. However what is happening when I run the query below is I get: DSmith1M4A Can someone figure out why this code is not working correctly? If there is not more than one "Smith" no integer is supposed to be returned. There is something in the "Captain Count" that I think is not working correctly. Code: [Select] /* * Gather captian information */ $strCaptainFirstInitial = substr($arrPost['cpt_first'],0,1); $strCaptainLastName = preg_replace("/[^a-zA-Z]/","",$arrPost['cpt_last']); $strCaptainName = strtolower($strCaptainFirstInitial.$strCaptainLastName); $sqlCaptainSearch = sprintf ( $strCaptainSearch, $strCaptainName ); $resCaptainSearch = mssql_query($sqlCaptainSearch,$conDB); /* * Create unique captain login and Password */ $strCaptainCount = (mssql_num_rows($resCaptainSearch) > 0) ? mssql_num_rows($resCaptainSearch) : "" ; $strLeagueTypeInitial = substr($arrLeagueSearch['type'],0,1); $strCaptainLogin = $strCaptainName . $strCaptainCount . $strLeagueTypeInitial . $arrLeagueSearch['size'] . $arrLeagueSearch['division']; Hello! I am busy developing a script that returns all users that have the cell "Available" set to 1 but I am unsure how to do this, I am familiar with basic SQL and I have made this: $sql = "SELECT * FROM `clans` WHERE `available` =1 LIMIT 0 , 30"; if ($result = mysql_query($sql)) { if (mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); echo ($row['name']); but it only displays information from the first row found, and I want it to display all the rows found, how can I do this? Thanks - GreenFanta This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306966.0 I have this query to show the current class I'm in: Code: [Select] $GetTimeTable = "SELECT * FROM timetable WHERE username='$username' AND Subject_date='$today_date'"; Then I have this to display current class: Code: [Select] if($TimeNow >= $Start_time && $TimeNow <= $End_time){ echo "Current Class: "; echo $Subject;} How would I find next class that day? Hi all, Just a pretty basic question that I can't find the asnwer to: I have a MySQL query of the following form: Code: [Select] $result = mysql_query (" SELECT $cols FROM tablename WHERE......."); Where $cols is as follows: Code: [Select] $cols = firstname, lastname, $price1, $price2, etc. ($price1 and $price2 are variable column names that contains prices) How do I find the lowest value for $price1 and/or $price2 out of the results set of this query? Thanks! soo i get info from a form and i want to search for it in my db .. if i find user_name AND user_password the $result returns true .. otherwise false .. <?php require_once("../includes/connection.php"); ?> <?php $user_name=$_POST["user_name"]; $user_password=$_POST["user_password"]; ?> <?php $query = "SELECT * FROM users WHERE '{$user_name}' = user_name AND '{$user_password}'= user_password "; $result = mysql_query($query,$connection); if($result==false){ redirect("../index.php");} elseif($result==true){ redirect("../welcome.php"); } ?> <?php //close connection! mysql_close($connection); ?> but the problem is that it always returns TRUE !!!! whats the problem here exactly ??? Hi Everyone. I get the following data from a result from database search <?php echo $rsjobs['CompanyURL'];?> It prints out the url but when I try to turn it into a clickable link it does not work Here is the coding I have so far. <a href="<?php echo $rsjobs['CompanyURL'];?>"><?php echo $rsjobs['CompanyURL'];?></a> What am I doing wrong ? please help. I´ve reached to
<?php require_once('Connections/conexxion.php'); ?> <?php mysql_select_db($database_conexxion, $conexxion); $query_consulta = "SELECT venta,compra,taller,regula_mas,regula_menos,movimiento.id_item,sum(compra+regula_mas-venta-taller-regula_menos) as stock, cilindro, esfera FROM movimiento join item on item.id_item=movimiento.id_item join rx on rx.id_rx=item.id_rx join cilindro on cilindro.id_cil=rx.id_cil join esfera on esfera.id_esf=rx.id_esf GROUP BY movimiento.id_item ORDER BY esfera desc, cilindro desc"; $consulta = mysql_query($query_consulta, $conexxion) or die(mysql_error()); $row_consulta = mysql_fetch_assoc($consulta); $totalRows_consulta = mysql_num_rows($consulta); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body> <?php echo "<table align=center>"; $columnes = 10; # Número de columnas (variable) if (($rows=mysql_num_rows($consulta))==0) { echo "<tr><td colspan=$columnes>No hay resultados en la BD.</td></tr> "; } else { echo "<tr><td colspan=$columnes>$rows Resultados </td></tr>"; } for ($i=1; $row = mysql_fetch_row ($consulta); $i++) { $resto = ($i % $columnes); # Número de celda del <tr> en que nos encontramos if ($resto == 1) {echo "<tr>";} # Si es la primera celda, abrimos <tr> echo "<td>$row[1]</td>"; if ($resto == 0) {echo "</tr>";} # Si es la última celda, cerramos </tr> } if ($resto <> 0) { # Si el resultado no es múltiple de $columnes acabamos de rellenar los huecos $ajust = $columnes - $resto; # Número de huecos necesarios for ($j = 0; $j < $ajust; $j++) {echo "<td> </td>";} echo "</tr>"; # Cerramos la última línea </tr> } mysql_close($connexion); echo "</table>"; ?> </body> </html> <?php mysql_free_result($consulta); ?>it "works", but results doesn´t start at number 1 but number 2 anyways, The intent of this table is to show the stock of a product, a lens, that has a range of Rx, we use to see this range this way, and show the stock this way would be very productive, but I can´t figure out how to achive it, any sugestion?? Edited by gralfitox, 16 December 2014 - 06:45 AM. I have a table korisnici in SQLite with INTEGER field aktivan that can have only 0 or 1 value (CHECK constraint). Field aktivan has value 0 but PHP returns value 1, why? Is this a bug? This is PHP code that I am running: $sql = "SELECT ime, aktivan FROM korisnici WHERE lower(ime) = '" . $ime . "'" . " AND sifra = '" . $_POST["sifra"] . "'"; $result = $db->query($sql); $row = $result->fetchArray(SQLITE3_ASSOC); $row['aktivan'] = 1 but in table the value is 0. When I run same query in DB Browser for SQLite I get correct value 0. Is this a bug? This topic has been moved to CSS Help. http://www.phpfreaks.com/forums/index.php?topic=353608.0 |