MySQL查询图片不显示、hover无stocknr,数据库图片读取问题求助
Let's tackle your problems one by one—there are a couple of obvious code issues plus some checks you should run:
1. Critical Loop Syntax Error (The Root Cause)
Your while loop has an extra semicolon at the end:
while($row1 = mysqli_fetch_assoc($result)); { ... }
That semicolon tells PHP to run an empty loop (it just fetches all rows without doing anything) and then execute the code in braces only once after the loop finishes. At that point, $row1 is false (since there are no more rows to fetch), so your $stocknr2 and $picname variables are either empty or invalid.
Fix: Remove the semicolon after while(...):
while($row1 = mysqli_fetch_assoc($result)) { ... }
2. Add Hover Stocknr Information
To show the stocknr when hovering over the image, add a title attribute to your <img> tag. This uses the $stocknr2 variable you already have:
echo "<img src='/upload/$upfile' border=1 width=350 height=280 title='$stocknr2'>";
3. Debug Database & Image Path Issues
Even if the loop is fixed, you might still have image loading problems. Here's how to debug:
- Check for MySQL errors: Always add error handling after
mysqli_queryto catch query issues:$result = mysqli_query($con,$sql1); if (!$result) { die("Query failed: " . mysqli_error($con)); } - Verify the
picfield value: Make sure thepiccolumn in yourstocktable stores the full correct filename (e.g.,imgpath.jpg, not just a partial path or empty value). You can test this by addingecho $picname;inside the loop to see what's being pulled from the database. - Confirm file permissions: Ensure the
/upload/directory and the image files inside have proper read permissions (usually755for directories,644for files) so the web server can access them. - Double-check the image path: You confirmed the image exists via
<img src='/upload/imgpath.jpg'>, so make sure$upfile(which is$picname) matches the exact filename in that path.
Full Corrected Code
Here's the code with all the fixes applied:
$sql1 = "SELECT pic, stocknr, status FROM stock WHERE status = '1'"; $result = mysqli_query($con,$sql1); // Add query error checking if (!$result) { die("Query failed: " . mysqli_error($con)); } // Fixed while loop (removed semicolon) while($row1 = mysqli_fetch_assoc($result)) { $stocknr2 = $row1['stocknr']; $picname = $row1['pic']; $upfile = $picname; echo "<center>"; echo "<a href='details.php?stocknr=$stocknr2'>"; // Added title attribute for hover info echo "<img src='/upload/$upfile' border=1 width=350 height=280 title='$stocknr2'>"; echo "</a>"; echo "</center>"; } mysqli_free_result($result);
Give these changes a try—most likely the extra semicolon was causing the bulk of your issues. If images still don't load after fixing that, use the debug steps above to narrow down the path/database value problem.
内容的提问来源于stack exchange,提问作者sean

