Reputation: 41
I was wondering how to show more then one picture from the database on a php document. I know hoe to put a picture into mysql and take out one of them but i don't know how to take out multiple (or all). Thanks in advance.
One of my php files looks like this
<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>
and then the getpic.php looks like this
<?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;
?>
So this code can tell the user to upload an image then show that image after adding it to the database, but how can i show multiple or all pictures in the database.
Thanks in advance.
Upvotes: 0
Views: 1705
Reputation: 819
Ok, here's some very basic code you can follow, but please read the BOLD NOTE at the end.
You could use multiple file inputs like this:
<input type='file' name='fileone'>
<input type='file' name='filetwo'>
...
and then you would call your insert for each file uploaded (or preferably loop, but this is more in line with the multiple inputs above):
$file = $_FILES['fileone']['tmp_name'];
... the rest of the insert code ...
$file = $_FILES['filetwo']['tmp_name'];
... the rest of the insert code ...
and then you would loop on the select when you pull the images out:
while ($row = mysql_fetch_assoc($image)) {
... the rest of your fetch code ...
}
BUT YOU SHOULD NEVER (almost never) STORE IMAGES IN A DATABASE!
Images should be stored on the filesystem for a few reasons:
Upvotes: 1