1

I am trying to print the image whose location is saved in my database, I have stored the absolute location in the database and not the relative one , I browsed through a lot of question including this one include a PHP result in img src tag I tried all the options that were given to the respective asker of the question but I didn't get my output, rest everything is being displayed apart from the image, its showing no file found

Here's my code, any help will be appreciated

while($result=@mysql_fetch_array($resul,MYSQL_ASSOC)){
    $image = $result['image'];
    echo $result['company'] . " " . $result['model'] . "<br>" ;
    echo '<img src="$image" height="50" width="50" />';
}

I know I am using mysql functions instead of mysqli but this code is not getting live ever.

Community
  • 1
  • 1
CAO
  • 129
  • 1
  • 11
  • 1
    Can you provide a sample output generated by this? I'm not going to talk about the mysqli, but please, stop using @'s :) – lsouza Aug 08 '13 at 18:28

2 Answers2

3

As watcher said, PHP does not do variable interpolation within single-quoted strings.

The most important feature of double-quoted strings is the fact that variable names will be expanded.

Read more about strings from the PHP manual.

Therefore, when you view the HTML, you will literally see this:

<img src="$image" height="50" width="50" />

Your code should be:

while($result = mysql_fetch_array($resul,MYSQL_ASSOC)) {
    $image = $result['image'];
    echo $result['company'] . " " . $result['model'] . "<br>";
    echo "<img src='$image' height='50' width='50'>";
}

Alternatively, interpolate the array value:

while($result = mysql_fetch_array($resul,MYSQL_ASSOC)) {
    echo $result['company'] . " " . $result['model'] . "<br>";
    echo "<img src='{$result['image']}' height='50' width='50'>";
}

If the filename contains spaces or other special characters, you may need to use rawurlencode(). In this case, you must concatenate the string since you are calling a function that returns a string value:

echo "<img src='" . rawurlencode($result['image']) . "' height='50' width='50'>";
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • This is what I am getting when I inspect the element for the image but there is nothing being displayed, now not even the error that says no file chosen, Its just the frame for the image – CAO Aug 08 '13 at 18:37
  • Yes I am running this locally and the file does exist here, when I inspect the element for this img tag I get the absolute location and when I click on that the image is displayed in a new tab – CAO Aug 08 '13 at 18:49
  • I did it but now the code became something like this but when I moved the image to the local directory of wamp i.e. in www the image is being displayed, thanks for your help, I really appreciate it. – CAO Aug 08 '13 at 18:58
1

PHP will not interpolate variables when you include them within single quotes. For more information, see the manual.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96