【发布时间】:2015-04-26 20:48:33
【问题描述】:
我正在尝试使用 PHP 和 MySQLi 将图像文件上传到我的数据库,但遇到了一个非常令人困惑的错误。该表有两列,“标题”和“图像”。 “标题”用于文件名,“图像”用于图像数据。两个表都不允许接受 NULL。当我上传文件时,数据存储在表格列中。 'title' 包含正确的值,但 'image' 列包含 '<binary data>'。
由于表格列不接受 NULL 值,我假设它是文件的数据,但是当我尝试在 showimage.php 中检索和显示图像数据时,它告诉我图像数据为 NULL。
我正在使用 BLOB 数据类型将图像数据存储在表中。就我而言,基于在线资源和示例,它应该可以工作。谢谢。
代码:
PHP:
上传.php
if (isset($_POST['submit'])) {
$title = $_FILES['image']['name'];
$data = $_FILES['image']['tmp_name'];
$content = file_get_contents($data);
$query = "INSERT INTO images (title, image) VALUES (?, ?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('sb', $title, $content);
$statement->execute();
$statement->store_result();
$creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($creationWasSuccessful)
{
echo "Works!";
} else {
echo 'failed';
}
}
showimage.php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = "SELECT * FROM images WHERE id = ?";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('i', $id);
$statement->execute();
$statement->store_result();
if ($statement->num_rows >= 1)
{
$statement->bind_result($imageid, $title, $image)
while ($statement->fetch()) {
if ($image == NULL) {
echo "Image data does not exist!";
} else {
header("Content-Type: image/jpeg");
echo $image;
}
}
}
}
HTML
<form action="uploads.php" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" name="submit">
</form>
【问题讨论】: