如何使用PHP从MySQL数据库获取图像

时间:2015-01-28 13:31:21

标签: php

我正在尝试从数据库中获取图像路径,并使用HTML <img>显示图像。

我在mysql数据库中保存图像的路径,但我无法理解什么是错误的。

HTML:

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>image</title>
    </head>

    <body>
        <img src="image_loading.php" width="100" height="100">
    </body>

</html>
<br />

PHP:

<?php
$dbhost     = "localhost";
$dbusername = "root";
$dbpass     = "";
$dbname     = "m_beg";

$conn = mysqli_connect($dbhost, $dbusername, $dbpass, $dbname) or die();
$sql = "SELECT `image` FROM `music_table` where `id`=100";

$res = mysqli_query($conn, $sql);
header("Location:image/jpg");

while ($row = mysqli_fetch_array($res)) {
    echo $row["image"];
}

?>

4 个答案:

答案 0 :(得分:0)

试试这样..

 while($row = mysqli_fetch_array($res))
        {
            $title = $row["image"];

            echo "<img src=$title width='100' height='100'>";
        }

答案 1 :(得分:0)

尝试在路径中添加正斜杠的相对URL路径:

<img src="/image_loading.php" width="100" height="100">

答案 2 :(得分:0)

这完全错了。它将尝试加载名为'image_loading.php'的图像。 php返回一个无效的标题。

相反,使用它,通过将php函数包含在你的html代码中,如果这是有道理的。

HTML

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>image</title>
    </head>

    <body>
        <img src="<?php echo getfilename();?>" width="100" height="100">
    </body>

</html>
<br />

PHP

    <?php
function getfilename()
{
    $dbhost     = "localhost";
    $dbusername = "root";
    $dbpass     = "";
    $dbname     = "m_beg";

    $conn = mysqli_connect($dbhost, $dbusername, $dbpass, $dbname) or die();
    $sql = "SELECT `image` FROM `music_table` where `id`=100";

    $res = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_array($res)) {
        return $row["image"];
    }
    return "";//error no image found
}
?>

答案 3 :(得分:0)

试试这段代码..

<?php
  $dbhost     = "localhost";
  $dbusername = "root";
  $dbpass     = "";
  $dbname     = "m_beg";

   $conn = mysqli_connect($dbhost, $dbusername, $dbpass, $dbname) or die();
   $sql = "SELECT `image` FROM `music_table` where `id`=100";

   $res = mysqli_query($conn, $sql);
   header("Location:image/jpg");

   //change this from mysqli_fetch_array to mysqli_fetch_assoc
   while ($row = mysqli_fetch_assoc($res)) {
    $image=$row['image'];
    echo "<img src='$image'>";
}


?>