PHP - 2nd Sql Query Also Returning Results From 1st Query
What would be the correct way to close a mysql query?
At current the second query below returns results from the 1st query AND the 2nd query The 3rd query returns results from the 1st, 2nd and 3rd query. etc etc. At the moment I get somthing returned along the lines of... QUERY 1 RESULTS Accommodation 1 Accommodation 2 Accommodation 3 QUERY 2 RESULTS Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 QUERY 3 RESULTS Takeaways 1 Takeaways 2 Takeaways 3 Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 Code: [Select] <!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" /> <?php include($_SERVER['DOCUMENT_ROOT'].'/include/db.php'); ?> <title>Untitled Document</title> <style type="text/css"> <!-- --> </style> <link href="a.css" rel="stylesheet" type="text/css" /> </head><body> <div id="listhold"> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Placestostay.html">Places To Stay</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Accommodation' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingout.html">Eating Out</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Restaurant' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingin.html">Eating In</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Takeaways' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------SKILLED TRADES BELOW---------------------------------------------------> <div class="list"><a href="Skilledtrades.html">Skilled Trades</a><br/> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Skilled Trades' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> Similar TutorialsGreetings all! I've been working on a project for about a week now and everything had been going fine until this evening. I'm querying a single row from a user information table based on the userID and doing various things based off of the information that is returned. For whatever reason, the query is not returning all of the information anymore. Code follows: Code: [Select] $userToEdit = mysqli_real_escape_string($GLOBALS['link'], $_POST['userToEdit']); $userSQL = "SELECT fName, lName, email, volunteer, staff, admin, active, volunteerID FROM userinfo WHERE userID=" . $userToEdit; $result = mysqli_query($GLOBALS['link'], $userSQL); if (!$result) { $message = 'There was an error retrieving the user information from the database.'; include '../html/error.html.php'; exit(); } $editInfo = mysqli_fetch_assoc($result); The strange part is that the database i'm querying is located on my remote host(GoDaddy). When I run the app from my local Apache server and query the remote DB, everything works fine, however, when I upload the files to my host, not all of the information is being returned. For example, using the print_r() function while on my local host, i get: Code: [Select] Array ( [fName] => Taylor [lName] => Hughes [email] => taylor@gmail.com [volunteer] => 1 [staff] => 0 [admin] => 0 [active] => 1 [volunteerID] => 13 ) But when I execute the app on my remote host, the print_r() function outputs: Code: [Select] Array ( [fName] => Taylor [lName] => Hughes [email] => taylor@gmail.com [volunteer] => [staff] => [admin] => [active] => [volunteerID] => 13 ) I'm not sure why this is happening but it is affecting multiple queries and subsequently multiple forms and functionality in different parts of the application. Any thoughts or suggestions would be greatly appreciated. I've browsed around for about an hour with no luck. I'm writing in PHP 5.3 and the remote MySQL DB is version 5.0 Oh! And if it helps, I just came to the realization that all the items not being returned are of the BIT data type in the tables. Hello all, Trying to figure out how to display database results so that they are numbered (for editing and deletion purposes). I want to be able to edit the message text and update the database information with the UPDATE command, but have not gotten that far yet. Current problem is that I am returning no results. Here is my script: Code: [Select] <!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=iso-8859-1" /> <title>My Profile</title> <link href="loginmodule.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>My Profile </h1> <a href="member-index.php">Home</a> | <a href="member-profile.php">My Profile</a> | Update Posts | <a href="logout.php">Logout</a> <br /><br /> <?php $subject = $_POST['subject']; $message_text = $_POST['message_text']; //Connect to mysql server $link = mysql_connect('XXXXXX', 'XXXXXX', 'XXXXXX'); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db('ryan_iframe'); if(!$db) { die("Unable to select database"); } // validate incoming values $subject = (isset($_GET['subject'])) ? (int)$_GET['subject'] : 0; $message_text = (isset($_GET['message_text'])) ? (int)$_GET['message_text'] : 0; ob_start(); $id = $_GET['SUBJECT']; $query = sprintf( " SELECT SUBJECT, MSG_TEXT, UNIX_TIMESTAMP(MSG_DATE) AS MSG_DATE FROM FORUM_MESSAGE WHERE SUBJECT = '$id' ORDER BY MSG_DATE DESC", DB_DATABASE, DB_DATABASE, $subject, $subject); $result = mysql_query($query) or die(mysql_error()); $num = mysql_numrows($result); mysql_close(); $i = 0; while ($i < $num) { $subject = mysql_result($result, $i, "SUBJECT"); $message_text = mysql_result($result, $i, "MSG_TEXT"); echo '<div style="width: 400px;padding:20px;">'; echo '<table border=0 width="400px">'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Date: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo date('F d, Y', $row['MSG_DATE']) . '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Subject: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo '<div>' . htmlspecialchars($row['SUBJECT']) . '</div>'; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Message: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo '<div>' . htmlspecialchars($row['MSG_TEXT']) . '</div>'; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo '</td>'; echo '<td style="vertical-align:top;width:320px;text-align:center;">'; echo '<form method="post">'; echo '<input type="hidden" name="update" value="true" />'; echo '<input type="submit" value="Update" />'; echo ' '; echo '<input type="hidden" name="delete" value="true" />'; echo '<input type="submit" value="Delete" />'; echo '</form>'; echo '</td>'; echo '</tr>'; echo '</table>'; echo '<br />'; echo '<hr />'; echo '</div>'; ++$i; } ?> </body> </html> Thanks in advance. Ryan Hello 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 SELECT i.item_id, i.title, i.price, i.p_and_p, SUM(i.price + i.p_and_p) AS `total_price`, i.listing, i.condition, i.start_date_time, i.listing_duration, CONVERT_TZ(DATE_ADD(i.start_date_time, INTERVAL concat(i.listing_duration) DAY), '+00:00', u.time_zone) AS `end_date_time` FROM items i LEFT JOIN sub_categories sc ON sc.sub_category_id = i.sub_category_id LEFT JOIN categories c ON c.name = 'test' JOIN users u WHERE u.username = 'Destramic' AND i.start_date_time < NOW() AND DATE_ADD(i.start_date_time, INTERVAL concat(i.listing_duration) DAY) >= NOW()I'm having a problem with my query returning more than 1 rows...I've even copied the row which is returning to see if that'll return 2 rows but it doesn't can anyone explain why this is happening please? Originally, I would get both, and unfortunately would inconsistently use both. Then, I wanted more consistently, so configured php.ini to only return objects as I felt accessing them was more concise. And then later, I found myself needing arrays more often, and initially would just typecast them to arrays but eventually my standard was to set the PDO's fetch style to an array. And now I find myself almost always explicitly requesting arrays and occasionally requesting columns or named values. Do you configure ATTR_DEFAULT_FETCH_MODE, and if so to what? PS. Anyone use FETCH_CLASS, FETCH_INTO or FETCH_NUM? If so, what would be a good use case? Moodle 2.5 *nix server Theme: Essential ---------------------- Hi Folks I have a small mind bender in how php is returning results from a mysql query. There are two issues: 1) The mysql query from phpmyadmin is correct, while the php function that handles the query from the website is not. 2) It takes a very long time to run this query with php, 30 seconds to over a minute. Phpmyadmin is rather quick (Query took 0.0239 seconds). The query is: SELECT u.firstname AS 'Name' , u.lastname AS 'Surname', c.shortname AS 'Course', ( CASE WHEN gi.itemname LIKE '%summative%' THEN 'SUMMATIVE' WHEN gi.itemname LIKE '%formative 2%' THEN 'FORMATIVE 2' ELSE 'MC' END) AS 'Assessment', from_unixtime(gi.timemodified, '%d/%m/%y') AS 'Date', IF (ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) > 70,'Yes' , 'No') AS Pass, ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark', ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark' FROM mdl_course AS c JOIN mdl_context AS ctx ON c.id = ctx.instanceid JOIN mdl_role_assignments AS ra ON ra.contextid = ctx.id JOIN mdl_user AS u ON u.id = ra.userid JOIN mdl_grade_grades AS gg ON gg.userid = u.id JOIN mdl_grade_items AS gi ON gi.id = gg.itemid JOIN mdl_course_categories AS cc ON cc.id = c.category WHERE gi.courseid = c.id AND gi.itemname != 'Attendance' AND u.firstname LIKE '%03%' AND gi.itemname LIKE '%mative%' ORDER BY `Name` , `Surname` , `Course`, `Assessment` ASCWhen I run the query in phpmyadmin , it gives back; Name Surname Category Module Course Assessment Date Competent Mark G03 Itumeleng Velmah Mokwa Fundamentals Communications CO1 119472 FORMATIVE 2 07/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO1 119472 SUMMATIVE 07/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO2 119457 FORMATIVE 2 05/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO2 119457 SUMMATIVE 05/04/14 Yes 88.00 G03 Lally Sheila Mokane Fundamentals Communications CO1 119472 FORMATIVE 2 07/04/14 NYC 59.00 G03 Lally Sheila Mokane Fundamentals Communications CO1 119472 SUMMATIVE 07/04/14 Yes 90.00 G03 Lally Sheila Mokane Fundamentals Communications CO2 119457 FORMATIVE 2 05/04/14 Yes 100.00 G03 Lally Sheila Mokane Fundamentals Communications CO2 119457 SUMMATIVE 05/04/14 Yes 98.00And it is perfect so I have no issues with that. Now in php I call; function print_overview_table_groups($COURSE, $choosegroup, $fromdate, $todate, $numarray) { global $DB; //check data if(!$choosegroup){ die('No Records To Display.'); } $thisgroup = $numarray[$choosegroup]; $sql = "SELECT DISTINCT u.firstname AS 'Name' , u.lastname AS 'Surname', (CASE WHEN cc.parent = '2' THEN 'Fundamentals' WHEN cc.parent = '3' THEN 'Core' WHEN cc.parent = '4' THEN 'Elective' END) AS 'Category', cc.name AS 'Module', c.shortname AS 'Course', (CASE WHEN gi.itemname LIKE '%summative%' THEN 'SUMMATIVE' WHEN gi.itemname LIKE '%formative 2%' THEN 'FORMATIVE 2' ELSE 'MC' END) AS 'Assessment', from_unixtime(gi.timemodified, '%d/%m/%y') AS 'Date', IF (ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) > 70,'Yes' , 'NYC') AS Competent, ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark' FROM mdl_course AS c JOIN mdl_context AS ctx ON c.id = ctx.instanceid JOIN mdl_role_assignments AS ra ON ra.contextid = ctx.id JOIN mdl_user AS u ON u.id = ra.userid JOIN mdl_grade_grades AS gg ON gg.userid = u.id JOIN mdl_grade_items AS gi ON gi.id = gg.itemid JOIN mdl_course_categories AS cc ON cc.id = c.category WHERE gi.courseid = c.id AND gi.itemname != 'Attendance' AND u.firstname LIKE '%03%' AND gi.itemname LIKE '%mative%' ORDER BY `Name` , `Surname` , `Course`, `Assessment` ASC"; return $DB->get_records_sql($sql); }This is returned to the index.php page from the function call; $lists = print_overview_table_groups($COURSE, $choosegroup, $fromdate, $todate, $numarray); print "<pre>"; print_r($lists); print "</pre>";The result is baffling... Array ( [G03 Itumeleng] => stdClass Object ( [name] => G03 Itumeleng [surname] => Mokwa [category] => Fundamentals [module] => Communications [course] => CO2 119457 [assessment] => SUMMATIVE [date] => 05/04/14 [pass] => Yes [mark] => 88.00 ) [G03 Lally] => stdClass Object ( [name] => G03 Lally [surname] => Mokane [category] => Fundamentals [module] => Communications [course] => CO2 119457 [assessment] => SUMMATIVE [date] => 05/04/14 [pass] => Yes [mark] => 98.00 ) )I only get one record for each student. Can anyone help me solve this? Regards Leon Ok, this may be just because I have been programming all day and my mind has gone blank (happens alot), but this is my PHP script: Code: [Select] <?php $query_distinct_item_types = mysql_query("SELECT DISTINCT name FROM item_types"); while($item_types = mysql_fetch_array($query_distinct_item_types)){ $distinct_item_types[] = $item_types['name']; } foreach($distinct_item_types as $item){ $query_item_total = mysql_query("SELECT item_type, SUM(price) WHERE item_type='$item' FROM costs GROUP BY item_type"); while($item_total = mysql_fetch_array($query_total_price)){ $item_totals[] = $item_total['SUM(price)']; } } $item_summery = $item_totals; ?> $item_summery which is = to $item_totals is returning null, any idea's? I'm having trouble with a simple SELECT query. I just cannot figure out what the problem is... <?php //Include database connection details include 'login/config.php'; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } $qry="SELECT * FROM members"; $result = mysqli_query($link, $qry); echo "<table>"; while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $getid = ($row['member_ID']); $firstname = ($row['firstname']); $lastname = ($row['lastname']); $email = ($row['email']); echo "<tr><td>$firstname</td><td>$email</td></tr>"; } echo "</table>"; ?> I know I have a connection to the DB, and I know that the query will return values as I have tested in in phpmyadmin. Can anyone see anything obvious I am missing? Thanks quick question, I have this code that returns over 100 buttons: Code: [Select] <?php // Query member data from the database and ready it for display $sql = mysql_query("SELECT * FROM products"); while($row = mysql_fetch_array($sql)){ $product = $row["product"]; $id =$row["id"]; $price =$row["price"]; ?> <div id="products"> <form action="" method="POST" name="myform<?php echo $id; ?>" class="myform<?php echo $id; ?>"> <input type="hidden" name="hiddenField" class="hiddenField" value="<?php echo $product; ?>" /> <input type="hidden" name="hiddenField2" class="hiddenField2" value="<?php echo $id; ?>" /> <input type="hidden" name="hiddenField1" class="hiddenField1" value="<?php echo $price; ?>" /> <input type="submit" name="submit" class="submit" value="<?php echo $product; ?>" style="background-color:lightgreen; height:50px; width:100px;"> </form> </div> <?php } ?> What I would like is for the buttons to form columns of nine. ie 9 buttons in a column then a new column form.... how do I do this? Can someone please give me some ideas as to what might be wrong with this query...I keep getting no result and am echoing $count for debugging (and usernames and passwords) but get nothing for $count (expecting a 0 or a 1) or $dbusername or $dbpassword $sql="SELECT * FROM `users` WHERE `User name` = '$fusername' and `Password` = '$fpassword'"; $result=mysql_query($sql); $dbusername=mysql_result($result,0,"User name"); $dbpassword=mysql_result($result,0,"Password"); echo $dbusername; echo $dbpassword; // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $fusername and $fpassword, table row must be 1 row echo $fusername; echo $fpassword; echo $count; if($count==1){ (This is where I keep going to the else) this is my query code Code: [Select] <?php $wsi_query = "(SELECT * FROM (SELECT a.no_Yards AS 'yards', a.Day_Swam AS 'date', a.Season AS 'season', (SELECT sum(no_yards) FROM swimming WHERE Season = '$ws') AS 'totalyards', (SELECT AVG(no_Yards) FROM swimming WHERE Season = '$ws') AS 'avg', (SELECT count(*) FROM swimming WHERE Season ='$ws') AS 'timelaps', (SELECT 1 + count(*) FROM swimming b WHERE b.no_Yards > a.no_Yards AND Season = '$ws') AS hrank, (SELECT 1 + count(*) FROM swimming b WHERE b.no_Yards < a.no_Yards AND Season = '$ws') AS lrank FROM swimming AS a) AS x WHERE Season = '$ws' )"; $wsi_result = mysql_query($wsi_query) or die("Query failed ($wsi_query) - " . mysql_error()); $wsi_row = mysql_fetch_assoc($wsi_result); ?> what it should do is output both the min and the max values like this Code: [Select] <?php while ($mm_wsi_row = mysql_fetch_assoc($wsi_result)){ if ($mm_wsi_row['hrank'] == 1){ if ($mm_wsi_row['date'] == "0000-00-00"){$dayswam = "";}else{$dayswam = $mm_wsi_row['date'];} echo "<tr>"; echo "<td style='background-color:#F90'>Max Length:</td>"; echo "<td>" . number_format($mm_wsi_row['yards']) . "</td>"; echo "<td>" . $dayswam . "</td>"; echo "</tr>"; } if($mm_wsi_row['lrank'] == 1){ if ($mm_wsi_row['date'] == "0000-00-00"){$dayswam = "";}else{$dayswam = $mm_wsi_row['date'];} echo"<tr>"; echo "<td style='background-color:#F90'>Min Length:</td>"; echo "<td style='background-color:#FF9'>". number_format($mm_wsi_row['yards']) . "</td>"; echo "<td style='background-color:#FF9'>" . $dayswam . "</td>"; echo "</tr>"; } ?> the problem is that it doesn't work right all the time for some it just shows the min while others it just shows max I've tested the query in MySQL workbench so i know that that is working right but idk why it works right for some and doesn't work for others Greetings, I need a bit of php coding help. I have a query that gives me results. What I need to do is take those results and, I think, use php to compare the results and add a 1 to the correct section. Example: 3 tables table name- retail_sales id sales_id amount week table name- online_sales id sales_id amount week table name- sales_person sales_id name I have the query that breaks down results by week: week 1 | retail_sales.amount | online_sales.amount What I need is some php code that will then compare the two together and: if retail_sales.amount > online_sales.amount +1 to retail OR if retail_sales.amount < online_sales.amount +1 to online so you would end up with a result like a sports record (6-2) Any ideas Thank you for any help Hi, say I have a query like so: foreach($_REQUEST['r'] as $position => $row) { $row = implode("', '",$row); $result = mysql_query("Insert into player_stats (position,shirt_number,player_id,goals,cards,substituted,used_sub,injury,season,report_id) values('$position','$row','$currentSeason','$report_id')"); } How do I print the results of that query to my Browser for each time? Thanks Code: [Select] $PlayerQuery = "SELECT FirstName, SurName FROM players p, rounds m, entrants e, games t WHERE p.PlayerID = e.PlayerID AND m.GameID = '$ID' AND e.EntrantID = m.Player"; $PlayerResult = mysql_query($PlayerQuery); $PlayerRow = mysql_num_rows($PlayerResult); Can someone suggest why this returns game*the number of results. For each new game it returns an extra duplicate result. For example for 2 games: j Smith j Smith t John t John etc There are no duplicate entry's! and results should be unique. Not in a loop (positive) Hi I have a query where it returns a few fields based on the location. I created a class for the function and an index page. It does not return any values. Can someone please advise/ THE CLASS Code: [Select] <?php /**************************************** * * WIP Progress Class * * ****************************************/ class CHWIPProgress { var $conn; // Constructor, connect to the database public function __construct() { require_once "/var/www/reporting/settings.php"; define("DAY", 86400); if(!$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD)) die(mysql_error()); if(!mysql_select_db(DB_DATABASE_NAME, $this->conn)) die(mysql_error()); } public function ListWIPOnLocation($location) { $sql = "SELECT `ProgressPoint.PPDescription` AS Description ,`Bundle.WorksOrder` AS WorksOrder, `Bundle.BundleNumber` AS Number, `Bundle.BundleReference` AS Reference,`TWOrder.DueDate` AS Duedate FROM `TWOrder`,`Bundle`,`ProgressPoint` WHERE `Bundle.CurrentProgressPoint`=`ProgressPoint.PPNumber` AND `TWOrder.Colour=Bundle.Colour` AND `TWOrder.Size=Bundle.Size` AND `TWOrder.WorksOrderNumber`=`Bundle.WorksOrder` AND `ProgressPoint.PPDescription` LIKE '" . $location . "%' ORDER BY TWOrder.DueDate DESC"; mysql_select_db(DB_DATABASE_NAME, $this->conn); $result = mysql_query($sql, $this->conn); echo $sql; while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $return[] = $row; } return $return; } } ?> The index page Code: [Select] <?php // First of all initialise the user and check for permissions require_once "/var/www/users/user.php"; $user = new CHUser(7); // Initialise the template require_once "/var/www/template/template.php"; $template = new CHTemplate(); // And create a cid object require_once "/var/www/WIPProgress/DisplayWIPOnLocation.php"; $WIPProgress= new CHWIPProgress(); $content = "Check WIP Status on Location <br>"; $content = "<form action='index.php' method='get' name ='location'> <select id='location' > <option>Skin Room</option> <option>Clicking</option> <option>Kettering</option> <option>Closing</option> <option>Rushden</option> <option>Assembly</option> <option>Lasting</option> <option>Making</option> <option>Finishing</option> <option>Shoe Room</option> </select> <input type='submit' /> </form>"; $wip = $WIPProgress->ListWIPOnLocation($_GET['location']); // Now show the details $content .= "<h2>Detail</h2> <table> <tr> <th>PPDescription</th> <th>Works Order</th> <th>Bundle Number</th> <th>Bundle Reference</th> <th>Due Date</th> </tr>"; foreach($wip as $x) { $content .= "<tr> <td>" . $x['Description'] . "</td> <td>" . $x['WorksOrder'] . "</td> <td>" . $x['Number'] . "</td> <td>" . $x['Reference'] . "</td> <td>" . $x['DueDate'] . "</td> </tr>"; } $template->SetTag("content", $content); echo $template->Display(); ?> thank you Hello all, I have made the multi level marketing downline tree, but the problem with it now, it gives only the downline of one result, as the query gives 2 results what I want now is to make it give the downline of both results not just one, and it's always 2 results, not more here is my code Code: [Select] <?php $id = $_GET['id']; $result = mysql_query("SELECT id FROM users WHERE id = '".$id."' ORDER BY id"); $row = mysql_fetch_assoc($result); if ($row['id'] == 0) { echo" <table> <div id=\".piccenter\""; echo "<tr>"; echo "<img src=\"icon.gif\" border=0 align=\"center\">"; echo ""; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$row['id']."'"; echo ""; echo "</div>"; } } $result2 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$row['id']."'"); $rows2 = mysql_fetch_assoc($result2); foreach ($rows2 as $row2) { if ($row2['id'] == 0) { echo" <div id=\".picleft\"> <img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0 >"; echo "<br />"; echo "'".$row2['id']."'"; echo "</div>"; echo " <td>"; echo "</td> "; } } $result3 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows2['id']."'"); $row3 = mysql_fetch_assoc($result3); if ($row3['id'] == 0) { echo"<div id=\".picright\"> <img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$row3['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result4 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$row3['id']."'"); $rows4 = mysql_fetch_assoc($result4); if ($rows4['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows4['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result5 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows4['id']."'"); $rows5 = mysql_fetch_assoc($result5); if ($rows5['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows5['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result6 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows5['id']."'"); $rows6 = mysql_fetch_assoc($result6); if ($rows6['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows6['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result7 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows6['id']."'"); $rows7 = mysql_fetch_assoc($result7); if ($rows7['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows7['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result8 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows7['id']."'"); $rows8 = mysql_fetch_assoc($result8); if ($rows8['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows8['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> "; } $result9 = mysql_query("SELECT id FROM users WHERE recruiteris = '".$rows8['id']."'"); $rows9 = mysql_fetch_assoc($result9); if ($rows9['id'] == 0) { echo"<img src=\"icon.gif\" border=0 align=\"center\">"; } else { echo "<img src=\"images.png\" border=0>"; echo "<br />"; echo "'".$rows9['id']."'"; echo ""; echo " <tr> <td>"; echo "</td> </tr> </tbody> </table> "; } ?> Below is my query which works fine: $query = " SELECT st.CourseId, c.CourseName, st.Year, st.StudentUsername, st.StudentForename, st.StudentSurname, s.ModuleId, m.ModuleName, m.Credits, s.SessionId, s.SessionWeight, gr.Mark, gr.Grade FROM Course c INNER JOIN Student st ON c.CourseId = st.CourseId JOIN Grade_Report gr ON st.StudentId = gr.StudentId JOIN Session s ON gr.SessionId = s.SessionId JOIN Module m ON s.ModuleId = m.ModuleId WHERE (st.StudentUsername = '".mysql_real_escape_string($studentid)."') "; Below is my results outputted by using php: Course: INFO101 - Bsc Information Communication Technology Year: 3 Student: Mayur Patel (u0867587) Module: CHI2550 - Modern Database Applications Session: AAB 72 (A) Course: INFO101 - Bsc Information Communication Technology Year: 3 Student: Mayur Patel (u0867587) Module: CHI2513 - Systems Strategy Session: AAD 61 (B) Course: INFO101 - Bsc Information Communication Technology Year: 3 Student: Mayur Patel (u0867587) Module: CHI2550 - Modern Database Applications Session: AAE 67 (B) How do I display it using php so that it only shows Course details and Student details only once, it will show each module in the course only once and shows each session being below each module it belongs to: The output from above should look like this in other words: Course: INFO101 - Bsc Information Communication Technology Year: 3 Student: Mayur Patel (u0867587) Module: CHI2550 - Modern Database Applications Session: AAB 72 (A) Session: AAE 67 (B) Module: CHI2513 - Systems Strategy Session: AAD 61 (B) PHP code to output the results: $output1 = ""; while ($row = mysql_fetch_array($result)) { //$result is the query $output1 .= " <p><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Year:</strong> {$row['Year']}<br/> <strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']}) </p>"; $output1 .= " <p><strong>Module:</strong> {$row['ModuleId']} - {$row['ModuleName']} <br/> <strong>Session:</strong> {$row['SessionId']} {$row['Mark']} ({$row['Grade']}) </p>"; } echo $output1; Thank You Hello all, I am new here so thank you in advance for all of your help. I am writing a pretty simple search script to display data from a table however have run into a snag. Things seem to get complicated all by themselves. I have a drop down to select the predetermined search criteria, because the data has either a 'Y'es or 'N'o. For example there are 50 or so products/brands with ingredients/categories in them. i.e. Brand X contains Sugar=Y, Salt=Y, Vinegar=N Brand Y contains Sugar=N, Salt=N, Vinegar=N Brand Z contains Sugar=Y, Salt=Y, Vinegar=Y Brand A contains Sugar=N, Salt=N, Vinegar=Y I want to display the brands that contain only the selected ingredients. I have added check boxes for the user to select. This runs ok however the return is more of a broader result and requires too much interpretation from the user. i.e. If I want to know which brands contain only salt and vinegar ??BRAND??= Sugar=N, Salt=Y, Vinegar=Y or ??BRAND??= Salt=Y, Vinegar=Y The return comes back: Brand X contains Sugar=Y, Salt=Y, Vinegar=N Brand Z contains Sugar=Y, Salt=Y, Vinegar=Y Brand A contains Sugar=N, Salt=N, Vinegar=Y Ideally the return Should only be: Brand Z contains Sugar=Y, Salt=Y, Vinegar=Y I believe the else if statement would work, I just have no knowledge of where to put it or how it would work. Any suggestions would be greatly appreciated. If ($_GET['CODE'] == '1') { $ThreadID = mysql_escape_string($_GET['threadid']); $ForumID = mysql_result(mysql_query("SELECT forum_id FROM ".FORUM_THREADS." WHERE thread_id='{$ThreadID}'", $db), 0, 'forum_id'); $PostText = mysql_escape_string($_POST['replytext']); $IP = $_SERVER['REMOTE_ADDR']; $PostQuery = "INSERT INTO ".FORUM_POSTS." (`user_id`, `thread_id`, `post_text`, `forum_id`, `ip_address`, `timestamp`) VALUES ('{$memid}', '{$ThreadID}', '{$PostText}', '{$ForumID}', '{$IP}' , CURRENT_TIMESTAMP)"; $PostRes = mysql_query($PostQuery, $db); For some reason whenever this query goes through, it also adds a blank result using all the same information but without any $PostTest so essentially it does query: Code: [Select] INSERT INTO ".FORUM_POSTS." (`user_id`, `thread_id`, `post_text`, `forum_id`, `ip_address`, `timestamp`) VALUES ('{$memid}', '{$ThreadID}', '', '{$ForumID}', '{$IP}' , CURRENT_TIMESTAMP) This is the only query that does this part of the code and I can't see why it is adding 2 queries. FORUM_POSTS = constant containing table name. I am able to run and display two queries I need for my program but having issues comparing the two result sets. If they are identical, means both tables are also identical (the query is for the table's schemas in MS-SQL) Here's the relevant part ... Code: [Select] //Variables $table_name=$_POST['table_name']; // Connect via Windows authentication $server = 'win1\i01'; //Connection info for PRO $connectionInfoPRO = array( 'Database' => 'adventureworks', 'CharacterSet' => 'UTF-8' ); $dbPRO = sqlsrv_connect($server, $connectionInfoPRO); if ($dbPRO === false) { exitWithSQLError('Database connection to PRO failed'); } //Connection info for ITG $connectionInfoITG = array( 'Database' => 'adventureworksCOPY', 'CharacterSet' => 'UTF-8' ); $dbITG = sqlsrv_connect($server, $connectionInfoITG); if ($dbITG === false) { exitWithSQLError('Database connection to ITG failed'); } /* Set up and execute the query. */ $query1 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table_name'"; // Run PRO query $qresult1 = sqlsrv_query($dbPRO, $query1); if ($qresult1 === false) { exitWithSQLError('Query of product data failed.'); } echo '<tr><th>NAME</th><th>TYPE</th><th>POSITION</th><th>DEFAULT</th><th>LENGHT</th><th>IS NULLABLE</th></tr>'; // Retrieve individual rows from the result while ($row1 = sqlsrv_fetch_array($qresult1)) { echo '<tr><td>', htmlspecialchars($row1['COLUMN_NAME']), '</td><td>', htmlspecialchars($row1['DATA_TYPE']), '</td><td>', htmlspecialchars($row1['ORDINAL_POSITION']), '</td><td>', htmlspecialchars($row1['COLUMN_DEFAULT']), '</td><td>', htmlspecialchars($row1['CHARACTER_MAXIMUM_LENGTH']), '</td><td>', htmlspecialchars($row1['IS_NULLABLE']), "</td></tr>\n"; } // null == no further rows, false == error if ($row1 === false) { exitWithSQLError('Retrieving schema failed.'); } //Run ITG query $query2 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table_name'"; $qresult2 = sqlsrv_query($dbITG, $query2); if ($qresult2 === false) { exitWithSQLError('Query of product data failed.'); } echo '<tr><th>NAME</th><th>TYPE</th><th>POSITION</th><th>DEFAULT</th><th>LENGHT</th><th>IS NULLABLE</th></tr>'; // Retrieve individual rows from the result while ($row2 = sqlsrv_fetch_array($qresult2)) { echo '<tr><td>', htmlspecialchars($row2['COLUMN_NAME']), '</td><td>', htmlspecialchars($row2['DATA_TYPE']), '</td><td>', htmlspecialchars($row2['ORDINAL_POSITION']), '</td><td>', htmlspecialchars($row2['COLUMN_DEFAULT']), '</td><td>', htmlspecialchars($row2['CHARACTER_MAXIMUM_LENGTH']), '</td><td>', htmlspecialchars($row2['IS_NULLABLE']), "</td></tr>\n"; } // null == no further rows, false == error if ($row2 === false) { exitWithSQLError('Retrieving schema failed.'); } How can I compare $row1 and $row2 here (the query results for each one) and validate if they both have same results, each and all columns. Any help is highly appreciated! |