0

我想知道如何在 php 文档上显示多张来自数据库的图片。我知道将图片放入 mysql 并取出其中一个,但我不知道如何取出多个(或全部)。提前致谢。

我的一个 php 文件看起来像这样

<html>
<head>
<title>Upload</title>
</head>

<form action='pictureuploadtest.php' method='POST' enctype='multipart/form-data'>
File: <input type='file' name='fileone'>
<input type = 'submit' name='submitfile'>
</form>

<?php
$con = mysql_connect("localhost", "username", "password") or die("Cannot connect: ".mysql_error());
mysql_select_db("testpicture") or die("Cannot connect to db: ".mysql_error());

$file = $_FILES['fileone']['tmp_name'];

if(!isset($file)) {
print "Choose an image";
} else {
$image = addslashes(file_get_contents($_FILES['fileone']['tmp_name']));
$imagename = addslashes($_FILES['fileone']['name']);
$imagesize = getimagesize($_FILES['fileone']['tmp_name']);


if($imagesize === false) {
echo "Invalid image.";
} else {
$insert = "INSERT INTO upload VALUES ('', '$imagename', '$image')";
if(mysql_query($insert, $con)) {
    $lastid = mysql_insert_id();
    echo "Image uploaded. <p /> Your image: <p /> <img src=getpic.php?id=$lastid width='300px' height='300px'>";
} else {
    echo "Cannot upload image: ".mysql_error();
}
}
}


?>

</html>

然后 getpic.php 看起来像这样

<?php
mysql_connect("localhost", "username", "password") or die("Cannot connect: ".mysql_error());
mysql_select_db("testpicture") or die("Cannot connect to db: ".mysql_error());


$id = addslashes($_REQUEST['id']);

$image = mysql_query("SELECT * FROM upload WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];


echo $image;

?>

因此,此代码可以告诉用户上传图像,然后在将其添加到数据库后显示该图像,但是我如何在数据库中显示多张或所有图片。

提前致谢。

4

1 回答 1

1

好的,这里有一些您可以遵循的非常基本的代码,但请阅读最后的粗体注释

您可以像这样使用多个文件输入:

<input type='file' name='fileone'>
<input type='file' name='filetwo'>
...

然后你会为每个上传的文件调用你的插入(或者最好是循环,但这更符合上面的多个输入):

$file = $_FILES['fileone']['tmp_name'];
... the rest of the insert code ...

$file = $_FILES['filetwo']['tmp_name'];
... the rest of the insert code ...

然后在拉出图像时循环选择:

while ($row = mysql_fetch_assoc($image)) {
... the rest of your fetch code ...
}

但是您永远不应该(几乎永远)将图像存储在数据库中!

出于以下几个原因,图像应该存储在文件系统中:

  1. 文件系统将更高效、更快:文件系统上的图像与系统上的 Web 服务器可以直接将图像从文件系统拉到 Web 服务器再发送给用户。在数据库中,它更多的是从文件系统,通过数据库层,(可能通过网络)到 Web 服务器,再到用户。
  2. 你不想打扰你的数据库)它可以做各种令人敬畏和令人印象深刻的事情,比如连接和子选择——如果它没有被浪费在直接提取大的二进制图像块上)与存储和检索图像这样微不足道的事情。
  3. 使用数据库的效率较低(在磁盘空间上),尽管随着存储成本接近 0,这确实变得越来越少。
于 2013-08-08T01:00:26.253 回答