我使用phpmyadmin创建了一个带有表的MySQL数据库。我创建了这个带有BLOB列的表来保存jpeg文件。
我在这里遇到了与php变量$result
有关的问题。
到目前为止我的代码:(catalog.php(:
<body>
<?php
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage FROM dvd WHERE id=1";
$result = mysql_query("$sql");
mysql_close($link);
?>
<img src="" width="175" height="200" />
</body>
如何将变量$result从PHP获取到HTML中,以便在<img>
标记中显示它?
你不能。您需要创建另一个php脚本来返回图像数据,例如getImage.php。将catalog.php更改为:
<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>
那么getImage.php就是
<?php
$link = mysqli_connect("localhost", "root", "", "dvddb");
$sql = "SELECT dvdimage FROM dvd WHERE id=?";
$result = mysqli_execute_query($link, $sql, [$_GET['id']]);
$image = mysqli_fetch_column($result);
header("Content-type: image/jpeg");
echo $image;
从技术上讲,也可以使用数据URI将图像数据放入img标记中。
<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />
在某些特殊情况下,这甚至可能有用,尽管在大多数情况下,你最好像戴斯科格建议的那样,通过单独的脚本来提供图像。
如果只存储文件名,而图像本身存储在文件中
while($row = mysqli_fetch_array($result)) {
echo 'img src="',htmlspecialchars($row['filename']),'" width="175" height="200" />";
}
使用PDO
查询
<?php
require 'connect.php';
$stmt = $pdo->query("SELECT * FROM products");
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
查看
<table>
<thead>
<tr>
...
<th>Product Name</th>
<th>Product Image</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product) : ?>
<tr>
...
<td><?= htmlspecialchars($product['product_name']); ?></td>
<td>
<img
src="data:image/jpeg;base64,<?= base64_encode($product['image']); ?>"
width="100"
height="100"
>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
在mysql_query((之后添加$row = mysql_fetch_object($result);
;
您的html <img src="<?php echo $row->dvdimage; ?>" width="175" height="200" />