PHP - Query Duplicate Results
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) Similar TutorialsI'm working on a directory component and have kind of a tricky thing I need to do. The list of results pop through ajax on the left side along with it's google map number tag, and the google map pops on the right side. To make it even trickier the results are popped through a radius search by proximity. The problem is if there are multiple results with the same address you end up having all of the number tags on the map buried under the last tag with that address, plus it makes for kind of a long list. What I need to do is run a check to see if the previous result is the same address, and if yes not pop that result in a new table cell, rather stick it in a jquery drop down div so that all of the following results with the same address are stuffed in the jquery drop down in the same table cell under the first result with that address. In a perfect world all of the listings with the same addresses would be submitted in order so I could just do a check for the previous itemid's address, but of course that's not the case. I thought about running a query to grab ALL of the addresses and then check the item's address against it to see if it matches and if yes echo the jquery div instead of the <td>, but obviously that won't work because that will cause the first item with that address to be put in the div also. Plus I don't know if that's a very efficient way to go about it anyway. Here's kind of the basic thing I'm working with: Code: [Select] $query = "SELECT data_txt FROM jos_sobi2_fields_data WHERE fieldid = 76 AND itemid = $mySobi->id"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ $myaddress = $row['data_txt']; } echo "<td $style>"; Any ideas? Hi there, I know I'm doing something stupid, but i've tried for hours to try and figure this out and I just cant seem to figure out why tutorials i've seen seem to work yet my own code doesnt. basically i've got two functions: getAll() and get($id) inside a class, calling getAll, returns an array with one of the same record as opposed to all the records (which is my intended result). Can anyone help? thanks. Code: [Select] class Test{ protected $_db; protected $_table = "table"; protected $_friends = array(); public function __construct($db) { $this->_db = $db; } public function getAll() { $db = $this->_db; $sql = "SELECT * FROM $this->_table"; $db->query($sql); while($data = $db->fetch_array()) { $this->_friends[$data['id']] = $this->get($data['id']); } return $this->_friends; } public function get($id) { $db = $this->_db; $sql = "SELECT * FROM $this->_table WHERE id='$id'"; $db->query($sql); $data = $db->fetch_array(); return (object)$data; } } $test = new Test(new mysqlConnClass()); $arrayOfAllAsObjects = $test->getAll(); Just finished a search script. However, when type two keywords it will return duplicate entries: Code: [Select] elseif(isset($_GET['search'])){ $search=$_POST['search']; $search=str_replace(" ", ".", $search); header("Location: ./index.php?q=".$search); } elseif(isset($_GET['q'])){ $search=$_GET['q']; $keywords=explode(".",$search); $sql10000="SELECT product_id FROM $tbl_name2 WHERE keyword LIKE '%" . implode("%' OR keyword LIKE '%",$keywords) . "%'"; $result10000=mysql_query($sql10000); if(mysql_num_rows($result10000)==0){ $content='<div class="center">Search found no results.</div>'; } else{ while($row10000=mysql_fetch_array($result10000)){ $product_id3=$row10000['product_id']; $sql15000="SELECT * FROM $tbl_name WHERE product_id=".$product_id3; $result15000=mysql_query($sql15000); while($row15000=mysql_fetch_array($result15000)){ extract($row15000); $content.=$product_name; } } } } I have 3 products: Test2 - microphone Test3 - audio, microphone Test123 - audio When you search "audio" you get: Test3, Test123 When you search "microphone" you get: Test2, Test3 When you search "audio microphone" you get: Test2, Test3, Test3, Test123 with Test3 being a duplicate. Is there anyway to correct this? I tried SELECT DISTINCT * FROM, but there's no difference in the results returned, from what I have now. Hey all, I've been re-developing a cracker for my site, and when i enter the hash to crack it displays the results 3 times. Example: http://www.just-hack.com/index.php?action=cracker Here's my source: Code: [Select] <?php /** * * @PHP Dictionary Cracker for SMF, v1.0 * */ function template_main() { echo " <table width='100%' border='0' cellspacing='0' cellpadding='4' align='center' class='tborder'> <tr class='catbg'> <td>Cracker</td> </tr> <tr> <td class='windowbg'> <div align='center'>"; function des($word) { return crypt($word, "sl"); } function undes($word, $hash) { $salt = substr($hash, 0, 2); return crypt($word, $salt); } if (!$_POST["encrypt"]) { if (!$_POST["decrypt"]) { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br />"; $hash = $_POST['hash']; } else { $hash = $_POST['hash']; if($hash==""){ echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Type a hash to Crack!</td></table><br />"; } else { if ($type == "DES") { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br />"; //DES } else { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br />"; $type = $_POST['type']; } } } } else { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br />"; $type = $_POST['type']; if ($type == "DES") { $word = strip_tags($_POST['word']); if($word == ""){ echo "<table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Type a word to encode!</td></table><br />"; } else { $enc = des($word); echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Encoded: <br /> $word = $enc</td></table><br />"; } } elseif ($type == "MD5") { $word = strip_tags($_POST['word']); if($word == ""){ echo "<table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Type a word to encode!</td></table><br />"; } else { $enc = md5($word); echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Encoded: <br /> $word = $enc</td></table><br />"; } } elseif ($type == "SHA1") { $word = strip_tags($_POST['word']); if($word == ""){ echo"<table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Type a word to encode!</td></table><br />"; } else { $enc = sha1($word); echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Encoded: <br /> $word = $enc</td></table><br />"; } } else { echo ("Error?!"); } } $hash = $_POST['hash']; $words = file("wordlist.txt"); foreach ($words as $word) { $word = rtrim($word); if (undes($word, $hash) == $hash) { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Plaintext found! <br /> $hash = $word</td></table><br />"; } } $file = "wordlist.txt"; $lines = count(file($file)); echo "There are $lines words in our wordlist!"; echo "</td></div></tr></table>"; } ?> Alright, I need to find a way to display the top ten duplicated rows for a table in my database. I have tried multiple methods but I have failed. Can you please assist me with this problem. I currently run a query in phpmyadmin to get the result, but i cant figure out how to properly code the php script. Hey guys just wondering if this piece of code is correct because i get a mysql error saying Duplicate entry '*********' for key 2 this is the code i have and table structure. $sql = " INSERT INTO `IP_Address` VALUES(NULL,'".$ip."','".$date."','".$time."') ON DUPLICATE KEY UPDATE `date` = `".$date."`, `time` = `".$time."` "; 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 The only 2 tables relevant to what I want to do are "User" and "Scores." Basically this database holds high scores for a project I've been working on. I only want to display 10 scores, all from different users. No 2 or more scores from the same user. This is my db structure within phpmyadmin: Quote database -> table -> X / User / Score / X / X / X / X / X / X / X / X If possible I'd like to run a query where it checks for duplicate entries by the same user and only show the highest score. The current query I'm running is below: $result = mysql_query("SELECT * FROM table ORDER BY Score DESC LIMIT 0, 10"); Is this possible? I can only seem to find information regarding the INSERT IGNORE clause and that obviously won't help me as the users and scores are already in the database. Thanks. 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> 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. 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! 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 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. 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 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 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. 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 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 |