简体   繁体   中英

MySQL query displays no results in HTML table with PHP

I'm trying to throw together a simple inventory database for a small customer of mine (I normally don't do WebDev stuff) but I'm a little stumped. I have what I think should work, but I get no results in my table. I know the query is good since I get the expected results when querying directly to the database, unless PHP expects different formatting of my SQL statement. here is my page:

<html>
 <head>
  <title>Inventory</title>
 </head>
 <body>
<?php
$con=mysqli_connect("localhost","user","pass","db_name");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


$query = "SELECT 
            products.name,
            products.sku,
            inventory.quantityfry,
            inventory.quantityjuv,
            inventory.quantityadult,
            inventory.notes,
            inventory.location,
            inventory.owner
          FROM 
            products
          INNER JOIN 
            inventory
          ON
            products.sku=inventory.sku";

$result = mysqli_query($query);
echo "<table border='1'>
<tr>
<th>Species</th>
<th>SKU</th>
<th>Fry Count</th>
<th>Juvie Count</th>
<th>Adult Count</th>
<th>Notes</th>
<th>Location</th>
<th>Owner</th>

</tr>";

while ($row = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['sku'] . "</td>";
    echo "<td>" . $row['quantityfry'] . "</td>";
    echo "<td>" . $row['quantityjuv'] . "</td>";
    echo "<td>" . $row['quantityadult'] . "</td>";
    echo "<td>" . $row['notes'] . "</td>";
    echo "<td>" . $row['location'] . "</td>";
    echo "<td>" . $row['owner'] . "</td>";
    echo "</tr>";
}

mysqli_free_result($result);

echo "</table>";

mysqli_close($con);
?> 
 </body>
</html>

When I load the page, all I see is my HTML table headers, but no data. No error messages, either. What am I missing?

you don't see error messages because you don't bother checking for them. You're calling mysqli_query incorrectly, and since you don't check for errors, never see them:

$result = mysqli_query($con, $query) or die(mysqli_error($con));
                       ^^^^---required  

Since you used it incorrectly, the query call returns false. You then blindly try to fetch result rows from that boolean FALSE, which would lead to further errors and your while() loop never executing at all.

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