使用php变量显示图像 [英] Displaying an image using a php variable

查看:94
本文介绍了使用php变量显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是什么:

$ image 是一个包含文本itemimg / hyuna.png 这是图像的路径。

  $ image ='itemimg / hyuna.png'; 

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

 < img src =< ;? $ image?> ALT = 测试/> 

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



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

 < H1> <?$ image?> < / H1> 

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



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

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

 < img src =itemimg / hyuna.pngalt =test/> 

完美显示图片。

所以现在我不知道为什么第一个代码只显示test中的文本alt =

额外问题:
如何从sql单元格向变量赋值?
我尝试了以下方法,但没有运气:

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

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

解决方案

首先,不应该使用PHP Shorttags。



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

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

但是我会鼓励将内容从这个变量中跳出:

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



您的额外问题:



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


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

Here is whats going on:

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

$image = 'itemimg/hyuna.png';

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

<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:

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

It displays itemimg/hyuna.png as a h1 banner.

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="

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

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

item is a table with a collumn: image which contains file paths to images

解决方案

First of all, you should not use PHP Shorttags.

When you use the PHP Shorttags you have to say:

<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'];

这篇关于使用php变量显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆