How to create and display image in PHP

两盒软妹~` 提交于 2020-05-17 05:12:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!