Home How to echo <img src with PHP variables as values of the src attribute
Reply: 4

How to echo <img src with PHP variables as values of the src attribute

Elizabeth Kof
1#
Elizabeth Kof Published in 2017-12-07 05:16:46Z

This question already has an answer here:

  • PHP Parse/Syntax Errors; and How to solve them? 12 answers

I am getting error when I try to echo image in PHP. Here is my code:

$sql = "SELECT id, title, filename FROM images";
$result = $conn->query($sql);


if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";

    echo '
    <img src = "'$pathx'.'$row["filename"]'">
    ';
    //filenames in database end with appropriate image extensions like .png

}

And I am getting this error: Parse error: syntax error, unexpected '$pathx' (T_VARIABLE), expecting ',' or ';' in C:\xampp\htdocs\display.php on line 29

I have checked solutions from similar questions from here on Stackoverflow and implemented some of the accepted answers still my problem is not solved.

meanwhile something like the code below works well. So why is the one above not working?

echo'<img src = "directory/images/girl-g2109_5_720.jpg">';
Abdulla Nilam
2#
Abdulla Nilam Reply to 2017-12-07 05:21:01Z

Do like this

$pathx = "directory/images/";
$file = $row["filename"];

echo '<img src="'.$pathx.$file.'">';

Output

<img src="directory/images/girl-g2109_5_720.jpg">
Bhupendra Mistry
3#
Bhupendra Mistry Reply to 2017-12-07 05:22:09Z
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";
    echo '<img src = "'.$pathx.$row["filename"].'">';
}

OR use can also use following way to render img tag

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/"; ?> 
    <img src = "<?php echo $pathx.$row["filename"] ?>">
<?php } ?>
RamC
4#
RamC Reply to 2017-12-07 05:23:58Z

It looks like there is an issue with the array concatenation.

The string '<img src = "' and variable $pathx are not concatenated properly.

There should be a concatenation operator ('.') in between.

Change the code to the following format to fix the issue.

Code

echo '<img src = "' . $pathx . $row["filename"] . '">';

Output

<img src="directory/images/girl-g2109_5_720.jpg">
Narendra Verma
5#
Narendra Verma Reply to 2017-12-07 05:35:27Z

Try this

There are multiple ways to display the image. You can also use like this.

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $image=$row["filename"];
?>
<img src="directory/images/<?php echo $image;?>">
<?php
}
 ?>

Output

<img src="directory/images/image_name.png">
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306119 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO