Reputation: 61
I'm having problems with SQL query that returns no results instead of the data from the tables. I have two tables on my DB, one is for Products and the other is Basket. The idea is to take the product id's from the basket and retrieve all the rest of the data from the product table. This is what i did:
$sql = sprintf("SELECT * FROM Basket");
$result = mysql_query($sql, $link);
while ($row = mysql_fetch_array($result)) {
$my_id = $row["Id"];
$prod_s=sprintf("SELECT * FROM Products WHERE Id='%s'",$my_id) ;
$prod= mysql_fetch_array($prod_s);
echo "<td>" . htmlentities($prod["Name"],ENT_QUOTES,"UTF-8") . "</td>";
echo "<td>" . htmlentities($prod["Size"]) . "</td>";
. . . The table is being created but all fields are empty.
Thank you!
Upvotes: 1
Views: 210
Reputation: 364
I think you still have to add a mysql_query for prod_s.
$my_id = $row["Id"];
$prod_s=sprintf("SELECT * FROM Products WHERE Id='%s'",$my_id) ;
$prod_q=mysql_query($prod_s);
$prod= mysql_fetch_array($prod_q);
echo "<td>" . htmlentities($prod["Name"],ENT_QUOTES,"UTF-8") . "</td>";
echo "<td>" . htmlentities($prod["Size"]) . "</td>";
Upvotes: 1
Reputation: 18520
First of all, your current code is vulnerable to second-level SQL injections: if one of the IDs in the database is a malicious string (e.g. the good old ; DROP DATABASE foo
), you're screwed.
Now, your actual problem is that you're not actually sending the second query to the SQL server. You'll want to run mysql_query()
on it and use the result handle with mysql_fetch_array
. You're already doing it correctly with the initial query. Just do the same thing again.
Finally, you might want to know that all of this can be done in a single SQL query, using joins. You may want to ask your favourite search engine about those. Good luck!
Upvotes: 1