使用 php 变量显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19563639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:43:02  来源:igfitidea点击:

Displaying an image using a php variable

phphtmlimagevariablesfilepath

提问by user1783150

I'm trying to display images by taking their file path from an sql table, but i'm having a lot of troubles.

我试图通过从 sql 表中获取它们的文件路径来显示图像,但是我遇到了很多麻烦。

Here is whats going on:

这是发生了什么:

$imageis a variable containing the text "itemimg/hyuna.png"which is path to an image.

$image是包含"itemimg/hyuna.png"作为图像路径的文本的变量。

$image = 'itemimg/hyuna.png';

I assumed I would be able to display the image outside of the php block like so:

我假设我能够在 php 块之外显示图像,如下所示:

<img src= "<? $image ?>" alt="test"/>

This doesn't work though for some reason.

尽管出于某种原因,这不起作用。

So I thought maybe it's not able to read the variable outside the php block(i'm a beginner), so for testing i did:

所以我想也许它无法读取 php 块之外的变量(我是初学者),所以为了测试我做了:

<h1> "<? $image ?>" </h1>

It displays itemimg/hyuna.pngas a h1 banner.

它显示itemimg/hyuna.png为 h1 横幅。

Meaning it's accessing the varible fine.

这意味着它正在访问变量罚款。

So I thought maybe the path is wrong. So I tried:

所以我想也许路径是错误的。所以我试过:

<img src= "itemimg/hyuna.png" alt="test"/>

This displays the image perfectly.

这完美地显示了图像。

So now I'm stuck scratching my head why the first bit of code displays nothing but the text "test"from "alt="

所以现在我被困在挠我的头为什么第一部分代码只显示"test"来自"alt="

Extra question:How do I go about assigning a value from an sql cell to a variable? I attempted the following with no luck:

额外问题:如何将 sql 单元格中的值分配给变量?我尝试了以下但没有运气:

$q = "select * from item where id=$id";
$results = mysql_query($q);
$row = mysql_fetch_array($results, MYSQL_ASSOC);
$image = ".$row['image'].";

itemis a table with a collumn: imagewhich contains file paths to images

item是一个带有列的表:image其中包含图像的文件路径

回答by andreashager

First of all, you should not use PHP Shorttags.

首先,您不应该使用 PHP Shorttags。

When you use the PHP Shorttags you have to say:

当您使用 PHP Shorttags 时,您必须说:

<img src="<?=$image ?>" alt="test" />

But i would encourage to escape the Content off the variable like this:

但我会鼓励像这样从变量中转义内容:

<img src="<?php echo htmlspecialchars($image); ?>" alt="test" />

Your extra question:

你的额外问题:

This should lead to an syntax error because the string could not be parsed, just use $image = $row['image'];

这应该会导致语法错误,因为无法解析字符串,只需使用 $image = $row['image'];

回答by Shankar Damodaran

Try this

尝试这个

<img src= "<?php echo $image ?>" alt="test"/>

<img src= "<?php echo $image ?>" alt="test"/>

回答by Taytay

try

尝试

<img src= "<?= $image ?>" alt="test"/>

or

或者

<img src= "<? echo $image; ?>" alt="test"/>

回答by prakash

try this

尝试这个

<img src= "<?php echo $image ?>" alt="test"/>