PHP - Adding 2 Results With 1 Query?
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. Similar TutorialsGreetings, 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 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 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> Hello, I have a database that contains a column with a int value for number of slots reserved, and what I want to do is fetch the value of each column and add them together to create one whole number. For example, in my database under preserved I have two separate values of 2 and 4.. I would like to take those two values and add them up into 6 through php... here is what I have so far: $slots = mysql_query("SELECT * FROM treservations WHERE reservation_date='$reservation_date' AND reservation_hour='$reservation_hour'") or die(mysql_error()); while ($row = mysql_fetch_assoc($slots)) { $row["preserved"]; } mysql_free_result($slots); Any help would be GREATLY appreciated.. if I need to add additional code please let me know. Thank you! I added a search form on my site but I cannot figure out how to add links to the search results.
The results are being posted as the item name and the item pages look like this used-product.php?Item=102
I am not understanding how I can have that url match up with my item name.
Here is my results.php code
In the header
<?php include_once('mysql_connect.php'); if (!isset($_POST['search'])) { header ("Location:index.php"); } $search_sql="SELECT * FROM new_equip WHERE itemname LIKE '% " .$_POST ['search'] . " %'"; $search_query=mysql_query($search_sql); if(mysql_num_rows($search_query)!=0) { $search_rs=mysql_fetch_assoc($search_query); } ?>and where the results are being displayed <?phpif (mysql_num_rows($search_query)!=0){ do {?> <p><a href="new-product.php?Item=<?php echo $eid; ?>"><?php echo $search_rs ['itemname']?></a></p> <?php } while ($search_rs=mysql_fetch_assoc($search_query)) ; } else { echo "No Results Found"; } ?>I have been on this and trying to figure out another issue I am having and I cannot figure out either of them. (The other is deleting a row from a table with the click of a link) Any help on this would be greatly appreciated it. I have looked and trial and error all day and I cannot seem to get it. Hi, Im trying to learn how to build a shopping cart system, im have a few problems and im not sure where im going wrong, it looks as though im getting an item into the session, but it looks like when i add another it over writing the first one, and im having trouble trying to echo it out. Here is what i have atm Code: [Select] session_start(); include('functions.php'); $pid = $_GET['product']; $q = $_GET['qty']; if($_GET['function']=="add") { echo "add " . $_GET['product']; $_SESSION['cart']=array(); $_SESSION['cart']['productid']=$pid; $_SESSION['cart']['qty']=$q; } print_r($_SESSION['cart']); echo showCart(); Am i way off on my code? regardless of how many things i try to add to session, all i can print out is the last one i entered. Cheers If there are two DataTime's which are exactly X seconds apart and the difference between those two DateTime's is added to a third DateTime, then the third DataTime's timestamp would change by exactly X seconds, true? Then why doesn't the second test below show those results, but is off by 1 day? <?php function test(string $start, string $end, string $newStart) { $startDt = new \DateTime($start); $endDt = new \DateTime($end); $intervalDt=$startDt->diff($endDt); $startSeconds=$startDt->getTimestamp(); $endSeconds=$endDt->getTimestamp(); $seconds = $endSeconds - $startSeconds; $dt = new \DateTime($newStart); $newStartSeconds=$dt->getTimestamp(); $dt->add($intervalDt); $newEndSeconds=$dt->getTimestamp(); $newSeconds = $newEndSeconds - $newStartSeconds; $newEnd = $dt->format(\DateTime::RFC3339); echo("original: $start => $end $endSeconds - $startSeconds = $seconds seconds<br>"); echo("new: $newStart => $newEnd $newEndSeconds - $newStartSeconds = $newSeconds seconds<br>"); echo("Error: seconds - newSeconds = ".($seconds - $newSeconds)); } test("2017-06-26T00:00:00Z", "2017-07-09T00:00:00Z", "2018-03-05T00:00:00Z"); echo('<br><br>'); test("2017-12-08T00:00:00Z", "2018-02-15T00:00:00Z", "2018-03-05T00:00:00Z");Quote
original: 2017-06-26T00:00:00Z => 2017-07-09T00:00:00Z 1499558400 - 1498435200 = 1123200 seconds
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) 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. 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) 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 Hi all, I'm new to php and I was trying to send the results of one query to another query. I need the results of both queries. Here are the queries $cui1 = mysql_query("SELECT DISTINCT CUI FROM MRSTY WHERE STY='ABC' "); $cui2 = mysql_query("SELECT DISTINCT CUI FROM MRSTY WHERE STY='XYZ' "); I want to know if this is possible $cuis = mysql_query("SELECT CUI1,CUI2,REL FROM MRREL WHERE CUI1 IN $cui1 OR CUI1 IN $cui2 "); Thanks. I was just wondering if this is a way that you can exclude certain rows from a MySQL query. For example if I have 10 records each with a unique id, is there anyway I can get all of the records except record 5? Thanks 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 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 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! Hello, This is query in MySQL Quote mysql> LOAD DATA LOCAL INFILE '/var/www/html/numbers.csv' INTO TABLE details FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (number); Query OK, 0 rows affected (0.00 sec) Records: 2200 Deleted: 0 Skipped: 1200 Warnings: 0 Now, I am trying to run the same query in PHP and display the same results.... (i.e. Records, Deleted, Skipped) Quote <?php $db=mysql_connect("localhost", "user", "1234") or die(mysql_error()); $dname="database"; mysql_select_db($dname)or die(mysql_error()); $sqlstatement="LOAD DATA LOCAL INFILE '/var/www/html/numbers.csv' INTO TABLE details FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (number)" ; mysql_query($sqlstatement) or die(mysql_error());; echo "it is done!"; ?> Tried mysql_fetch_array, row but could not get it to work... please help guys 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> "; } ?> |