【问题标题】:Displaying an image where image path stored in Database using Id,使用 Id 显示图像路径存储在数据库中的图像,
【发布时间】:2014-12-10 03:01:48
【问题描述】:

我正在尝试在网页上显示图像,其中图像路径存储在数据库中,图像存储在服务器中。但我无法使用以下代码显示这些图像,所以请有人帮我解决这个问题,..

<form method="post"  enctype="multipart/form-data" action="file_upload.php">
<table>

<?php

$dbhost = 'xxxxxxxx';
$dbuser = 'xxxxxxxxx';
$dbpass = 'xxxxxxxxxx';
$db_name = 'xxxxxxxxxx';
$tbl_name = 'xxxxxxxxxxx';


$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("$db_name")or die("cannot select DB");

$path1 = mysql_query("select * from '$tbl_name' where id='1'");
$path2 = mysql_query("select * from '$tbl_name' where id='2'");
$path3 = mysql_query("select * from '$tbl_name' where id='3'");

echo '<tr><td><img src="$path1"></td>' ;
echo '<td><img src="$path2"></td>' ;
echo '<td><img src="$path3"></td></tr>' ;

?>

</table>
</form>

【问题讨论】:

  • 您需要使用 mysql_fetch_assoc 之类的函数遍历结果集 $path1,然后选择列 $path1['image_path']

标签: php html mysql database image-processing


【解决方案1】:

在我们开始之前有几件事:

  • 我推荐使用 mysqli,并将在下面的示例中使用(mysql 为 deprecated
  • 我将使用循环来遍历结果,而不是单独查询每个元素。

PHP 代码

$dbhost = 'xxxxxxxx';
$dbuser = 'xxxxxxxxx';
$dbpass = 'xxxxxxxxxx';
$db_name = 'xxxxxxxxxx';
$tbl_name = 'xxxxxxxxxxx';


$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

if (!$conn)
{
    die('Could not connect: ' . mysqli_connect_error());
}

$result = mysqli_query($con, "SELECT * FROM `$tbl_name`");

while ($row = mysqli_fetch_array($result))
{
    echo '<tr><td><img src="'.$row['image'].'"></td>' ;
}

请注意我是如何首先从查询中“获取”结果的。该查询首先返回一个 mysqli 对象,该对象包含 所有 查询返回的结果。这些必须被提取;我介绍的方法也广泛用于其他地方的示例。

还要注意在引用表格时如何使用反引号字符而不是单引号。

【讨论】:

  • 感谢我不理解的代码 $img_base = 'path/to/images';
  • 我假设您的文件夹设置是这样的:/path/to/images/image.jpg。我稍微编辑了我的代码。通过首先将'path/to/images/'分配给$img_base,然后将实际图像文件分配给$img_item,我们可以将它们连接在一起以获得图像的url。
【解决方案2】:

mysql_query();有 2 个参数。

argument1:连接。
argument2:查询。

如果我是你,我会这样做:

$sql = "select * from `$tbl_name` where `id` between 1 and 3";
$path = mysql_query($conn, $sql);
while($row = mysqli_fetch_array($patht)) {
echo '<tr><td><img src="' . $row['name of colum'] . '"></td></tr>' ;
}
mysql_close($con);

抱歉我的英语不好。我是荷兰人。

【讨论】:

  • 感谢echo $row['word']中的“单词”是什么代码
【解决方案3】:

执行查询后,我们将得到结果集游标。我们需要对其进行迭代以获取所有行。 试试下面的代码,它应该可以工作。

$result = mysql_query("SELECT * FROM  '$tbl_name' WHERE id IN ( 1, 2, 3 ) ");

if (!$result) {
// show your respective error messages
}else{
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr><td><img src="'.$row['database_column_name'].'"></td>' ;
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多