我正在尝试将我的代码转换为 mysqli
准备,但在从数据库中检索特定数据的图像时遇到问题。举例来说,id 1
将在同一页面中发布它的图像。
你们能检查一下我的代码吗? 我正在尝试查看特定数据的图像。你们能帮我吗?谢谢,这是我的代码:
这是我表单中的代码:
<form action="upload_photo.php" method="POST" enctype="multipart/form-data">
<div class="col-md-6">
<div class="alert alert-info" role="alert"><span class="glyphicon glyphicon-user" aria-hidden="true"></span> Add/Update Photo</div>
<input type="hidden" name="id" value="<?= $id; ?>" />
<input type="file" name="image"><br>
<input type="submit" value="Upload Image" name="submit">
</div>
<div class="row">
<div class="col-md-6 col-md-3">
<a href="#" class="thumbnail">
<img src="image_view.php?id=$id" alt="...">
</a>
</div>
Updated Photo
</div>
</form>
这是我的 php 上传图像的代码:
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['submit'])) {
$imageName = mysqli_real_escape_string($conn, $_FILES["image"]["name"]);
$imageData = mysqli_real_escape_string($conn, file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysqli_real_escape_string($conn, $_FILES["image"]["type"]);
if (substr($imageType, 0,5) == "image") {
$query = "UPDATE `crew_info` SET `image_name` = ?, `updated_photo` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'ssi', $imageName, $imageData, $_POST['id']);
mysqli_stmt_execute($stmt);
$id = $_POST['id'];
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
这是我检索图像的代码,但它对我不起作用:
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['id'])) {
$id = mysqli_real_escape_string($_POST['id']);
$query = "SELECT * FROM `crew_info` WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 's', $_POST['id']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $first_name, $middle_name, $last_name, $age, $month, $day, $year, $birth_place, $gender, $martial_status, $religion, $nationality, $email_address, $address_1, $address_2, $course, $school_graduated, $remarks, $date_added, $crew_status, $image_name, $updated_photo);
while (mysqli_stmt_fetch($stmt)) {
sprintf("%s", $updated_photo);
}
header("content-type: image/jpeg");
sprintf("%s", $updated_photo);
}
else {
echo "Bad";
}
?>
图片正在上传,但无法检索。请大家帮帮我,谢谢
最佳答案
这里有一些问题:
- 在您的 html 中使用
<img src="image_view.php?id=$id" alt="...">
。这会向服务器发出 GET 请求,因此您需要$_GET['id']
而不是$_POST['id']
在输出图像的脚本中。 - 您不应该使用
mysqli_real_escape_string()
当您使用准备好的语句时,mysqli 将在您执行准备好的语句时处理这一点。此外,在使用它来获取图像的脚本中,您不会将数据库连接作为第一个参数,这样它也会失败。编辑:您似乎没有使用转义值,因此您可以简单地删除该行。
除此之外,您可能应该:
- 将图像作为文件存储在文件系统中。如果内容不敏感/ protected ,您可以将其放在网络服务器根目录中的某个位置,以便您可以轻松包含指向它的链接。这将使数据库维护和备份变得更加容易。
- 如果您使用现在使用的方法,则仅在显示图像时获得您需要的内容。这将使您的代码更易于阅读,并且当您执行以下操作时,新列不会引入错误:
SELECT updated_photo FROM crew_info WHERE id = ?
.
关于php - 如何使用 mysqli 准备从数据库检索图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37582690/