PHP - Getting Result From A Select Sum If Query
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
Similar TutorialsHello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads Okay so, I'm adding a reply feature to my text-board, and I'm wondering how I can select a single result from the DB I've tried this $board = mysql_real_escape_string($_GET['board']); $thread = mysql_real_escape_string($_GET['thread']); $result = mysql_query("SELECT subject, name, id, timestamp, body FROM $board LIMIT $thread,$thread"); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { printf("<div id='html1' style='background-color:#F0E0D6;border:solid 1px #800000;font-family:arial; font-size: 12px; padding:2px; margin:2px;'><font color='#CC1105'>%s </font><font color='#117743'>%s</font> <font color='#800000'>Post # %s - %s<br />%s<br /></div>", $row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6]); mysql_free_result($result); } ?> Kinda works but if I pu ?thread=56 then it would show thread 57, which in this example does not exist. $result = mysql_query("SELECT * FROM `friend_system` WHERE `friend_system_accepter` = '$myusername' "); echo mysql_num_rows($result);This displays the total rows in the table. $result = mysql_query("SELECT COUNT(friend_system_accepter) FROM `friend_system` WHERE `friend_system_accepter` = '$myusername' "); echo mysql_num_rows($result);This displays '1', which is incorrect. I want to echo out the number of rows where 'friend_system_accepter' = $myusername Thanks Hello.
I'm having some issues with a select statement containing ABS().
Here's the select query:
"SELECT gadenavn, husnr, ABS(husnr - $husnr) AS husnr_range, postnr,db, shaping, dsl_node, ctr_node, db_ctr_luftlinje, bynavn FROM `TABLE 1`, Post_numre WHERE `postnr`=`postnummer` AND `gadenavn`=`$vejnavn` AND `postnr`=`$postnr` AND `husnr`>0 ORDER BY husnr_range ASC LIMIT 5"Now lets asume my variable "$husnr" is a value of 15. In my table I have the values for coulmn "husnr": 13,12,11,10,9 What really bugs me is the outcome doing af simple "while loop" is returning the values 12,11,10,9. What happened to 13?! printing the "husnr_range" values shows "3,4,5,6". What puzzles is the row missing, as I only get 4 results, with a "LIMIT 5". Can anyone explain why the last resulst isn't included? 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 I am trying to update a mysql table called AvItems with the value 'Torso' in the Equip "section?" I have been through the forums and cannot see anything to match. I dont mind if the page looses the onsubmit() and has a button instead. Though I would like to update the database and link back to the same page: There is a display that shows the item that is currently equiped, I have put this in to show it works, or doesn't as the case may be. Hope I got the code /code right this time. many thanks in advance Andy Curtis Code: [Select] create table Items( ItemID integer unsigned auto_increment primary key, ItemName varchar(20) not null, Type varchar(10), UsedOn varchar(10), ); create table AvItems( AvItemID integer unsigned auto_increment primary key, AvID integer unsigned, ItemID integer unsigned, Equip varchar(8)); <?php $username="root"; $password="MyPassword"; $database="MyDataBase"; $AvName = "AndyJCurtis"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $AvAccR = mysql_query( " SELECT AvID FROM AvAcc WHERE AvName = '$AvName' " ); $AvID = mysql_result($AvAccR, 0, 'AvID'); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $Torso = mysql_query(" select ItemName from AvItems, Items where AvItems.itemID = Items.itemID AND AvItems.AvID = '$AvID' AND UsedON = 'Body' "); $TorsoE = mysql_query(" select ItemName from AvItems, Items where AvItems.itemID = Items.itemID AND AvItems.AvID = '$AvID' And UsedON = 'Body' AND Equip = 'Body' "); if(mysql_num_rows($TorsoE) != 0) { $TorsoItem = mysql_result($TorsoE ,0,"ItemName"); //mysql_close(); ?> <title></title> <head></head> <body> <form action="http://localhost/CI/Equip2.php" method="post"> <table border=1> <tbody> <tr> <td>Torso<BR> <?PHP echo "$TorsoItem <BR>"; ?> <select name="Torso" onchange="submit();" value =" Update"> <?PHP while($TorsoRow = mysql_fetch_array($Torso)) { echo "<option value=\"".$TorsoRow['ItemName']."\">".$TorsoRow['ItemName']."\n </option>"; } ?> </select> </td> </tr> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// <?php if($_POST['Torso'] == 'Update') { mysql_query("update AvItems set Equip = '' where Equip='Torso'") or die("cant update unequip"); mysql_query("update AvItems set Equip = 'Torso' where ItemID='{$_POST['ItemName']}'") or die("cant update equip"); } ?> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// </tbody> </table> </.form> </body> </html> 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! 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. 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 Hey guys. Me again... Essentially what i am doing is pulling data from a MySQL database about the number of thumbnails on a page. The user can then change this using a <select> dropdown menu. How ever, i want the <select> to default to the amount already specified by the Database. I know i can do this by inserting a Selected attribute to one of the <options> but what is the best way of doing this? Heres my code.. $NumberOfThumbnails = mysql_result($data, 0,"NumberOfThumbnails"); <select name="numberofthumbnails"> <option value="0">None</option> <option value="2">2</option> <option value="4">4</option> <option value="6">6</option> <option value="8">8</option> <option value="10">10</option> <option value="12">12</option> <option value="14">14</option> <option value="16">16</option> <option value="18">18</option> <option value="20">20</option> <option value="22">22</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> </select> Thanks - Danny 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>'; } } ?> 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! 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']; 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', ), ), ), ); ?> This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306966.0 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 When I run 'select 1700-price as blah from goldclose as t2 order by dayid desc limit 1' by itself in mysql I get a numerical result: one row, one column. In my php script, the 1700 is actually a variable. so here it is $changequery = sprintf("select $goldprice-price as change from goldclose order by dayid desc limit 1"); $change = mysql_query(changequery); while ($row = mysql_fetch_array($change)) { printf("$row[0]"); } mysql_free_result($changeresult); I get the following error, Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>/root/fuzzy/htmlmain4.php on line 99 Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in <b>/root/fuzzy/htmlmain4.php on line 103 Not sure why? All i want is to get the result of that select statement into a variable such as $change Hi, I have come up with the following code, I need it to get the details of several scattered products and echo the results, the trick is I don't want it to echo the results one after the other... I want to have the products scattered between unique text on the page but don't want to run the query several times for performance reasons. E.g.- PAGE to look like this: $Product_1 unique text/images $Product_2 $Product_3 unique text/images $Product_4 Current Code: Code: [Select] <? $result = mysql_query("SELECT * FROM products where Product_ID IN (475, 465, 234, 567, 845)"); while($row = mysql_fetch_array($result)) { $x = "1"; while ($x<=3) { echo $x; $Product = "Product_"; $Product = $Product.$x; echo $Product; $Product = $row['Product_ID']; echo $Product; $x++; echo $x; } } At the moment it returns the following results: Quote 1 Product_1 465 2 2 Product_2 465 3 3 Product_3 465 4 1 Product_1 475 2 2 Product_2 475 3 3 Product_3 475 4 A few problems... In Blue... it duplicates for product 465 In Red... It repeats again for 475 Also.... it starts with 465, but I want it to go in order as how it appears - $result = mysql_query("SELECT * FROM products where Product_ID IN (475, 465, 234, 567, 845)"); so should start with 475 I want to get the following result: Quote 1 Product_1 475 2 2 Product_2 465 3 3 Product_3 234 4 4 Product_4 567 4 (and so on.....) If anyone could provide me assistance with my troubled 'while loop' statement that would be much appreciated! |