问题
I would like to display an image using PHP. Here is what I have tried, but it does not work.
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<div class="container">
<?php
$img_name = echo $row['img_name']; //I get it from the database
img_block($img_name); //Display the image here.
//Function to display image
function img_block(img_src) {
// e.g. img_src = cat.jpg;
$img_input = "images/" . img_src;
$set_img = '<img class="media-object-ph" src="'.$img_input.'" width="380" height="290" alt="...">';
return $set_img;
}
?>
</div>
</body>
</html>
Thank you in advance.
回答1:
Too long for a comment... You have a number of errors:
$img_name = echo $row['img_name'];
should be:
$img_name = $row['img_name'];
You are calling your function but not doing anything with the return value, you need to echo it:
img_block($img_name);
should be:
echo img_block($img_name);
Finally you have not put the required $ on the img_src variable in your function; it's definition should be:
function img_block($img_src) {
// e.g. img_src = cat.jpg;
$img_input = "images/" . $img_src;
$set_img = '<img class="media-object-ph" src="'.$img_input.'" width="380" height="290" alt="...">';
return $set_img;
}
If you make all these changes, and (e.g.) $row['img_name'] = 'image1.jpg', your code will output:
<img class="media-object-ph" src="images/image1.jpg" width="380" height="290" alt="...">
Demo on 3v4l.org
来源:https://stackoverflow.com/questions/61569289/how-to-create-and-display-image-in-php