tags:

views:

69

answers:

4

I have a database which is tied to a server of pictures. In the case that a pic isn't uploaded I want to place an "unavailable" photo in its place. Each pic is in numerical order based on the primary key from the database $row['Item_ID']. My script below searches for the file but can't find any pics, so it uses the "unavailable" for everything. I am not sure if I can use double quotes on the first line when I write '$row["Item_ID"]'.

$img_var = '$row["Item_ID"]';
$item_img = '/item_images/$img_var.jpg';         
if (!file_exists($item_img))        
{ $row['Item_ID'] = 'unavailable'; }     
else { $row['Item_ID'] = $row['Item_ID']; }
+2  A: 

Single quotes are not interpolated.

EFraim
+2  A: 

This

$img_var = '$row["Item_ID"]';
$item_img = '/item_images/$img_var.jpg';

needs to read

$img_var = $row["Item_ID"];
$item_img = "/item_images/$img_var.jpg";

or even

$item_img = "/item_images/{$row["Item_ID"]}.jpg";

When it's inside single-quotes, PHP doesn't resolve $img_var to its value, it just uses the string "$img_var".

Mark Biek
+5  A: 

Your first two lines are needlessly performing (or attempting-to perform) string replacement.

Single-quote delimited strings aren't interpolated for variables or escape sequences.

But really, you're emaking this overly complex - just concatenate the filepath on a single line and and fail-over to your unavailable image when you need to.

$item_img = '/item_images/' . $row["Item_ID"] . '.jpg';
if ( !file_exists( $item_img ) )
{
  $item_img = '/item_images/unavailable.jpg';
}
Peter Bailey
A: 
$item_img = '/item_images/'.$row['Item_ID'].'.jpg';
if(!file_exists($path_to_root.$item_img)) {
    $item_img = '/item_images/unavailable.jpg';
}

Note the $path_to_root. Your HTML root is not the sames as your PHP root (unless your server is specifically configured that way... mine isn't), so you have to make sure the paths are correct. I like to place a PHP file sitting at the base of my site with define('ROOT', dirname(__FILE__)); and then you can just do ROOT.'/path/to/whatever.jpg'.

Mark