Reputation: 319
I am trying to use php to display images based on the id of the item. This is for an ecommerce store, I am having difficulty figuring it out however. This is the php I have:
<?php
$product_list = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysql_num_rows($sql);
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$pid = $row['id'];
$product_name = $row["product_name"];
$price = $row["price"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "HERE IS WHERE THE IMAGE <strong>$product_name</strong> - $$price - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
In theory, I was trying to add, where the text HERE IS WHERE THE IMAGE is to use:
<img src='../inventory_images/$pid.jpg' />
However this and other variations that I tried did not work. How the image is uploaded is that the variable "$pid" is the id of the product, and the .jpg ending is added, here is the code to explain that:
$pid = mysql_insert_id();
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
So theoretically simply by having the product id I can get the image out using $pid... that just isn't working. Ideas? Thanks in advance!
Upvotes: 0
Views: 1442
Reputation: 3886
It looks like you have an error in your output as well, could you try to replace that line:
$product_list .= "HERE IS WHERE THE IMAGE <strong>$product_name</strong> - $$price - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
With that line:
$product_list .= "HERE IS WHERE THE IMAGE <strong>$product_name</strong> - \$$price - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$pid'>edit</a> • <a href='inventory_list.php?deleteid=$pid'>delete</a><br />";
Upvotes: 1
Reputation: 843
I see that you discovered that your image was not actually there so I thought I'd share this with you. You can check if this file exists quite easily:
if (file_exists ('../inventory_images/' . $pid . '.jpg')) {
$product_image = '<img src="../inventory_images/' . $pid . '.jpg">';
} else {
$product_image = '<img src="../inventory_images/image_not_found.jpg">';
}
Then simply use that $product_image variable in your $product_list where you need it. You could also modify the else statement and work in some error handling (update a field in a DB, send you an email, etc...).
Hope this helps.
Upvotes: 1