【发布时间】:2019-05-10 16:10:29
【问题描述】:
我不知道为什么我的图片没有显示在我的index.php 页面中。
我使用 PDO 连接和使用数据库,但我遇到了一些以前从未发生过的奇怪问题。我以 blob 类型存储在数据库中的图像未显示在我的 index.php 页面中。
这是我的代码:
<?php
$dsn = 'mysql:host=localhost;dbname=website;charset=utf8mb4';
$pdo = new PDO($dsn, 'root', '');
if ( isset($_POST['upload']) )
{
$file = addslashes(file_get_contents($_FILES['image']['tmp_name']));
if ( !empty($file) )
{
$sql = " INSERT INTO images(name) VALUES (:name) ";
$pdo->prepare($sql)->execute(array('name' => $file));
}
}
?>
我用它在我的 images div 标签上显示图像:
<div class="images" id="Images">
<?php
$sql = " SELECT * FROM images ";
$result = $pdo->query($sql);
if ( $result->rowCount() > 0 )
{
while ( $row = $result->fetch() )
{
echo '<img src="data:image/jpeg;charset=utf-8;base64,' .base64_encode($row['name']). '" alt="Binary Image"/>';
}
}
?>
</div>
【问题讨论】:
-
您已经在使用
addslashes将二进制图像数据传递到数据库之前对其进行了更改。我认为这样做不是你想要的。此外,当您将二进制数据存储在 blob 字段中时,请在表架构中将该字段标记为BINARY(找不到我现在想到的 Q&A)。另请参阅:stackoverflow.com/q/6346319/367456 (2011), stackoverflow.com/q/14734812/367456 (2013) 和 Large Objects (LOBs) - PDO manual。