【发布时间】:2017-01-26 11:50:24
【问题描述】:
我在从 mysql 数据库获取图像并在网页上显示时遇到问题。 我有一个 user_image 表,其中包含用户 ID、图像(blob 数据类型)、标题、图像名称(图像名称,例如 0101.jpg)、时间(图像上传的时间戳)。 用户可以将图像上传到数据库并根据时间戳查看他们的图像。 关于如何在网页上显示图像的任何输入? 代码如下:
<?php
session_start();
$con = mysqli_connect("localhost", "root", "","login") or die("Unable to connect to MySQL");
$userid = $_SESSION['userid'];
$sql = "SELECT image,image_name,caption FROM user_image WHERE userid=$userid";
if($query = mysqli_query($con, $sql)) {
while($row=mysqli_fetch_array($query)) {
header('Content-type: image/jpeg');
echo $row["image"];
}
}else{
echo "Error";
}
$con->close();
?>
上传图片到数据库的代码如下:
<?php
session_start();
if (isset($_POST['submit'])){
echo $_SESSION["userid"];
$userid = $_SESSION["userid"];
$con=mysqli_connect("localhost","root","","login")or die("Unable to connect to MySQL");
$caption = $_POST['Caption'];
$imageName = mysqli_real_escape_string($con,$_FILES["fileToUpload"]["name"]);
$imageData = mysqli_real_escape_string($con,file_get_contents($_FILES["fileToUpload"]["tmp_name"]));
$imageType = mysqli_real_escape_string($con,$_FILES["fileToUpload"]["type"]);
echo $imageName;
echo $imageType;
if(substr($imageType,0,5) == "image"){
$stmt = mysqli_prepare($con, "INSERT INTO user_image (userid,timestamp, image, image_name,caption) VALUES (?,now(), ?, ?,?)");
if ($stmt === false) {
trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($con)), E_USER_ERROR);
}
$bind = mysqli_stmt_bind_param($stmt, "isss", $userid,$imageData, $imageName, $caption);
if ($bind === false) {
trigger_error('Bind param failed!', E_USER_ERROR);}
$exec = mysqli_stmt_execute($stmt);
if ($exec === false) {
trigger_error('Statement execute failed! ' . htmlspecialchars(mysqli_stmt_error($stmt)), E_USER_ERROR); }
}
else
{
echo " only images are allowed";}
}
$con->close();
?>
【问题讨论】:
-
好吧,一些可以构成网页的 HTML 将是一个好的开始
-
欢迎来到 SO。请阅读What topics can I ask about 和How to ask a good question 和the perfect question 以及如何创建Minimal, Complete and Verifiable example SO 是不是免费的编码或代码转换或调试或教程或图书馆查找服务 你还必须展示你已经为解决自己的问题付出了一些努力。
-
@RiggsFolly - 请您详细说明一下。我不明白你在问什么。
-
查看用于将图像作为 blob 存储在表中的代码会很有用
-
一般来说,您不希望将文件存储在数据库中。这是缓慢且不必要的。一种常见的方法是将上传的文件复制到一个新的基本上随机名称的文件夹中。该表存储原始名称、类型、大小等信息。显示图像很简单,因为文件已经存在于磁盘上。您需要做的就是检索他们的位置和名称,其余的由浏览器完成。