简体   繁体   中英

Html table returns empty after SQL query

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!

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 (eg 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!

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>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM