使用PHP从数据库显示图像

使用PHP从数据库显示图像,php,html,database,image,Php,Html,Database,Image,我在显示保存在数据库中的URL的图像时遇到问题 这是我的HTML源代码: <div id="posts"> <img id="images" src="php/getImage.php?id=1"> <footer> <a href="php/getImage.php?id=1" download><p>Download</p></a> </footer> </div&g

我在显示保存在数据库中的URL的图像时遇到问题

这是我的HTML源代码:

<div id="posts">
<img id="images" src="php/getImage.php?id=1">
<footer>            
<a href="php/getImage.php?id=1" download><p>Download</p></a>
</footer>
</div>
和我的getImage.php文件:


带问题的代码使用了mysql\u query/mysql\u fetch\u数组,这在PHP中已不再使用。即使使用不推荐的mysql_*版本,此部分

mysql_fetch_array($result);
echo "images/$result"; 
已发布代码的数量应为

$row = mysql_fetch_array($result, MYSQL_ASSOC); 
echo "images/".$row["image"];
我还没有测试这段代码,因为我机器上的PHP版本高于5.5,不支持mysql扩展

每一行都需要从SQL查询的result$result中提取。从获取的行$row中,可以使用列标题图像访问每个单元格

在getimage.php中尝试以下代码

<?php
    $id = $_GET['id'];

    $db = new mysqli("host", "username", "password", "DB name");
    $sql = "SELECT image FROM images WHERE imageID=$id";

    $result=$db->query($sql);

    $row = $result->fetch_assoc();

    echo 'images/'.$row['image'];
?>

仅供参考,mysqli支持过程编程和面向对象编程范式

这里有多个问题:

1停止使用Mysql_uu函数,仅使用mysqli_uuu函数或PDO。Mysql\uPHP功能已被弃用,不再受支持,并且已经5年多没有使用过了!。这是不安全的,只会变得更糟

2您的PHP文件只是回显一个字符串,images/someimagename.jpg;这不是图像文件,您需要输出此文件名字符串的内容

3您当前的SQL易于SQL注入,并且当前非常不安全。您的数据库很容易被恶意网页访问者破坏/滥用

4您的mysqli_fetch_数组需要为要使用的数组中的值分配一个变量

5在DB身份验证中使用单引号而不是双引号,这样特殊字符,例如$,尤其是密码中的$,就不会被PHP误解

上述问题的解决办法: 如果未启用,则有多种其他可能更详细的方法使用或输出图像类型

请注意: 您的图像URL是相对的,因此,由于文件getImage.php位于php文件夹中,因此请求的图像将位于php/images/path中。如果这不是存储图像的位置,则需要调整图像路径URL并使其正确,或者使用强烈建议的方法


如何存储图像??您是将图像存储在dir中,并将其相对路径存储在db中,还是将图像作为blog存储在db中?不要使用mysql.*。它已弃用且不安全!您正在将mysqli_*与mysql_*混合。我正在将图像的名称存储在我的数据库中的字段image下,并尝试通过回显images/$result images/来输出图像,该文件夹也是我保存图像的文件夹。请将此输入您的答案。另外,您还需要将$db作为一个对象,别忘了。
<?php
// id is assumed to be an integer value.
// This prevents SQL injection and database compromise by forced
// typecasting of the data to integer.
$id = (int)$_GET['id'];

$db = mysqli_connect('host', 'username', 'password', 'DB name');
$sql = "SELECT image FROM images WHERE imageID=".$id." LIMIT 1"; 

// only use mysqli_ functions.
$result=mysqli_query($db, $sql);

// assign to a $variable
$output = mysqli_fetch_array($result);

//The [ relative :( ] URL of the resoure requested:
$file = "images/".$output['image'];

// Before the data is output we need to set the correct header so the 
// browser knows what sort of file to expect.
$image_mime = image_type_to_mime_type(exif_imagetype($file));    
header("Content-type: " . $image_mime);

// Grab and output the raw data in the filepath stored in the URL.
print readfile($file);

// If this is the end of thefile you should not use a closing PHP tag.   
// ?>