Upload multiple images to Database MYSQLI - php

I am planning to have a web gallery. However, it is hard for me to use PHP to insert DB. The following code:
HTML -- I want to make a form which has category and multiple images that can be inserted into DB at the same time.
<form action="upload" method="POST" enctype="multipart/form-data">
<p> Upload : <input type="file" id="file" name="images" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<p> <input type="submit" name="submit" value="Upload!" /> </p>
</form>
DATABASE
I am using imageName as VARCHAR not BLOB TYPE.
PHP
<?php
include ("dbConnect.php");
if(isset($_POST["submit"])) {
$image = $_POST['images']['tmp_name'];
$imageName = $_POST['images']['name'];
$imageSize = $_POST['images']['size'];
$imageType = $_POST['images']['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
?>
The problem is, the category is the only one has inserted into the database successfully. But not with the imageName, imageType, and imageSize. And also i want the image to be stored into database so that I can retrieve the image from DB on the other web page. Any ideas?

You can use 'multiple' property in the 'input' tag like this :
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" multiple='multiple' /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
User can select multiple files and upload them.
And at the server you will do this :
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageName = $_FILES['userfile']['name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
$imageCategory = $_POST['imageCategory'];
$len = count($image);
$path = "images/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType) VALUES ('$imageName[$i]', '$imageCategory', '$imageSize[$i]' , '$imageType[$i]' )");
}
}
}
}
$mysqli->close();
header("location: index");

First off the file information won't be in the $_POST global variable it will be in the $_FILES
From http://php.net/manual/en/features.file-upload.multiple.php (modified):
Form
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" /> </p>
<p> <input name="userfile[]" type="file" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
Parse the global file variable to an array (we'll assume this is a helper function called parseFiles.php):
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Move the files and insert the file information into the database :
<?php
include ("dbConnect.php");
include ("parseFiles.php");
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$image = $file['tmp_name'];
$imageName = $file['name'];
$imageSize = $file['size'];
$imageType = $file['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
}
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
Hopefully that should do the job. I've not tested this I've just blind coded it so there may be some bugs

Related

[PHP][MySQL] How to implement a title field for each selected file in an upload form?

I'm a php/mysql newbie and need your help!
I have an upload formula to upload multiple files to a database, selected one by one.
The files upload works fine, but I want to add a title field for each selected file. I have no idea how to implement this in my code.
Here is my code:
$db = mysqli_connect("localhost", "root", "", "xy");
if (isset($_POST['upload_docs'])) {
for($mi = 0; $mi < count($_FILES['sel_doc']['tmp_name']); $mi++) {
$doc = $_FILES['sel_doc']['name'][$mi];
$tmp_doc = $_FILES['sel_doc']['tmp_name'][$mi];
$target = "doc_uploads/". basename($doc);
if (move_uploaded_file($tmp_doc, $target)) {
echo "Upload successfully!";
}
else {
echo "Upload failed!";
}
$sql_f = "INSERT INTO docs (doc_file) VALUES ('$doc')";
mysqli_query($db, $sql_f);
}
}
<form method="POST" action="upload.php" enctype="multipart/form-data">
<div>
<input type="file" name="sel_doc[]">
<input type="file" name="sel_doc[]">
<input type="file" name="sel_doc[]">
<input type="file" name="sel_doc[]">
<input type="file" name="sel_doc[]">
</div>
<div id="upload_button">
<button type="submit" name="upload_docs">upload</button>
</div>
</form>
This is how 1 upload would looks like:
| id_doc | doc_file | doc_title|upload_id|
++++++++++++++++++++++++++++++++++++++++++++++++
|.....1......|...a.pdf...|....vvv....|....1....|
|.....2......|...b.pdf...|....www....|....1....|
|.....3......|...c.pdf...|....xxx....|....1....|
|.....4......|...d.pdf...|....yyy....|....1....|
|.....5......|...e.pdf...|....zzz....|....1....|
In my orginal code I insert in 2 tables for 1:n realationship (because of the "upload_id").
HTML
<div>
<?php for ($i=0; $i<5; $i++){ ?>
<b><?php echo $i ?></b><br>
File: <input type="file" name="sel_doc[<?php echo $i ?>]"><br>
Title: <input name="title[<?php echo $i ?>]"><br>
<?php } ?>
</div>
Will print this:
<div>
<b>0</b><br>
File: <input type="file" name="sel_doc[0]"><br>
Title: <input name="title[0]"><br>
<b>1</b><br>
File: <input type="file" name="sel_doc[1]"><br>
Title: <input name="title[1]"><br>
<b>2</b><br>
File: <input type="file" name="sel_doc[2]"><br>
Title: <input name="title[2]"><br>
<b>3</b><br>
File: <input type="file" name="sel_doc[3]"><br>
Title: <input name="title[3]"><br>
<b>4</b><br>
File: <input type="file" name="sel_doc[4]"><br>
Title: <input name="title[4]"><br>
</div>
PHP code
$db = mysqli_connect("localhost", "root", "", "xy");
if (isset($_POST['upload_docs'])) {
for($mi = 0; $mi < count($_FILES['sel_doc']['tmp_name']); $mi++) {
$doc = $_FILES['sel_doc']['name'][$mi];
$tmp_doc = $_FILES['sel_doc']['tmp_name'][$mi];
$target = "doc_uploads/". basename($doc);
$title = (isset($_POST['title'][$mi])?$_POST['title'][$mi]:"");
if (move_uploaded_file($tmp_doc, $target)) {
echo "Upload successfully!";
}
else {
echo "Upload failed!";
}
$sql_f = "INSERT INTO docs (doc_file, title) VALUES ('$doc', '$title')";
mysqli_query($db, $sql_f);
}
}
Btw; This example code is not safe for sql injection.

Multiple upload images PHP & Mysql

Below code uploads images one by one. I want to upload multiple images!
<?php
//config
require("./configuration.php");
$id = $_GET['id'];
$q = mysql_query("SELECT * FROM books WHERE id='$id'") or die(mysql_error());
$row = mysql_fetch_array($q);
$name = $row['name'];
echo '<div class="center-top"> NAME: <strong style="font-size:22px;">'.$name.'</strong> </div>';
//begin upload
if(isset($_POST['submit']))
{
$title = htmlspecialchars($_POST['title']);
$path = "./upload/images/";
$name_pic = $_FILES['file']['name'];
$ext = strtolower(substr(strrchr($name_pic, "."), 1));
$allow = array("jpg", "jpeg", "JPG", "JPEG", "png", "gif");
$uptype = ($_FILES['file']['tmp_name']);
if (in_array($ext, $allow))
{
$rand = rand(0,10000);
$md5 = md5($rand);
$new_file_name = "{$md5}.{$ext}";
$move_file = move_uploaded_file($_FILES['file']['tmp_name'], $path.$new_file_name);
if($move_file) {
mysql_query("INSERT INTO images (id, link, title, bid)
VALUES (NULL, '$new_file_name', '$title', '$id')") or die (mysql_error());
echo "<div class='yes'>succesfully added!</div>";
}}}
//form
echo '
<form method="post" action="images.php?id='.$id.'" enctype="multipart/form-data">
<br />title: <br /><input type="text" name="title" value="'.$name.'"/><br />
<br /><br/><input name="file" type="file" />
<br /><input type="submit" name="submit" value="UPLOAD" /><br /><br />
</form>
';
?>
With this code delete an image:
<?php
$id = $_GET['id'];
$result = mysql_query("DELETE FROM imagesWHERE `id`='$id'");
echo "<div class='yes'>successfully deleted picture!</div>";
?>
First of all, you need to declare <input name="file" type="file"/> as <input name="file[]" type="file" multiple/>
Then, find total nos of images selected. Put it in for loop and start storing in your upload->images folder and save image path in images column.
<?php
//config
require("./configuration.php");
$id = $_GET['id'];
$q = mysql_query("SELECT * FROM books WHERE id='$id'") or die(mysql_error());
$row = mysql_fetch_array($q);
$name = $row['name'];
echo '<div class="center-top"> NAME: <strong style="font-size:22px;">'.$name.'</strong> </div>';
if(isset($_POST['submit']))
{
$title = htmlspecialchars($_POST['title']);
$path = "./upload/images/";
$TotalImage = count($_FILES['file']['name']);
for($i=0;$i>$TotalImage;$i++)
{
$image_name = $_FILES['file']['name'][$i];
$new_file_name = $path.$image_name;
if(move_uploaded_file($_FILES['file']['tmp_name'][$i],$path.$image_name))
{
mysql_query("INSERT INTO images (id, link, title, bid) VALUES (NULL, '$new_file_name', '$title', '$id')") or die (mysql_error());
echo "<div class='yes'>succesfully added!</div>";
}
}
}
//form
echo '
<form method="post" action="images.php?id='.$id.'" enctype="multipart/form-data">
<br />title: <br /><input type="text" name="title" value="'.$name.'"/><br />
<br /><br/><input name="file[]" type="file" multiple/>
<br /><input type="submit" name="submit" value="UPLOAD" /><br /><br />
</form>
';
?>

How to insert multiple photos and multiple text fields into mysql database?

Plain and simple. I want to create a form that first of all inserts all fields values into the MySQL database. Second of all, I want to give users options to upload multiple images. but the code below wont insert image into the database. I am totally lost. don't know what else might be wrong with this code.
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post" enctype="multipart/form-data">
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<input type="FirstN" name="Firstname" >
<input type="LastN" name="Lastname" >
<input type="submit" value="Upload all files">
</form>
<?php
if(isset($_POST['submit'])) {
if(isset($_FILES['file_array'])) {
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 0; $i < count($tmp_name_array); $i++) {
if(move_uploaded_file($tmp_name_array[$i], "test_uploads/".$name_array[$i])) {
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
$sql = "INSERT INTO image, FirstName, LastName VALUES ('{FirstN}','{LastN}','{file_array}')";
}
?>

Rename an image during the uploading in php

Am trying to rename an image during upload i know i am met to put the function rand() and end() but i just do not know where to put it here is my code below
php / html section
if (isset($_POST['uploadimage'])) {
list($typed) = $_FILES['images']['type'];
if(!ereg("image",$typed)){
echo "<div class='msg1'>File is not an image or field is empty</div>";
}else{
$pixsname = $_FILES['images']['name'];
while(list($key,$value) = each($_FILES['images']['name'])){
if(!empty($value)) {
$pixsname = $value;
$add = "./img/venues/$pixsname";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
}
$image = new Image();
$image->load("$add");
$image->resize(652,300);
$image->save("$add");
}
echo "<div class='msg1'>Image profile has been updated</div>";
}
}
form method="post" enctype="multipart/form-data" id="loginform" >
<input type="hidden" name="MAX_FILE_SIZE" value="200000000">
<input type="file" name="images[]" id="fileField" class="field_ss"/>
<?php echo $pix; ?>
<input type="submit" name="uploadimage" value="Upload Image"/>
</form>
Replace
$pixsname = $value;
with
$pixsname = 'The_New_Name_Of_Your_Picture';

Multiple image upload

i have a problem in multiple image upload, when i upload, there's only 1 image which go to the targeted directory and database. i need two images to go directory and database...any help please?
this is my form
<form action="test.php" method="post" enctype="multipart/form-data">
Keywords: <input style="margin-left:35px;" type="text" name="keyword" /><br />
Name: <input style="margin-left:60px;" type="text" name="name" /><br />
Name2: <input style="margin-left:60px;" type="text" name="name2" /><br />
Categorie: <input style="margin-left:40px;" type="text" name="categorie" /><br />
Lieu: <input style="margin-left:70px;" type="text" name="lieu" /><br /><br />
<input type="file" name="file[]" multiple="multiple" /><input type="file" name="file_2[]" multiple="multiple"/><input type="submit" name="submit" value="Upload" />
</form>
<?php
$connect = mysql_connect("localhost", "root", "");
$select_db = mysql_select_db("yakatrouver_test", $connect);
if(#$_POST['submit']){
$keywords = $_POST['keyword'];
$name = $_POST['name'];
$name2 = $_POST['name2'];
$categorie = $_POST['categorie'];
$lieu = $_POST['lieu'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_type = $file['type'];
$file_size = $file['size'];
$file_path = $file['tmp_name'];
$file_2 = $FILES['file_2'];
$file_name_2 = $file['name'];
$file_type_2 = $file['type'];
$file_size_2 = $file['size'];
$file_path_2 = $file['tmp_name'];
if($file_name!="" && ($file_type="image/jpeg"||$file_type="image/png"||$file_type="image/gif") && $file_size<=2000000)
if(move_uploaded_file ($file_path, 'pictures_uploaded/' .$file_name))
$query = mysql_query("INSERT INTO `user_input`(keyword, name, categorie, lieu) VALUES ('$keywords', '$name', '$categorie', ' $lieu')");
$query = mysql_query("UPDATE `user_input` set image='pictures_uploaded/$file_name' WHERE `name`='$name'");
if($query == true)
{
echo "file Uploaded";
}
}
$result = mysql_query("SELECT * FROM `user_input` WHERE `image`=''") or die(mysql_error());
while($row = mysql_fetch_array($result))
?>
Try:-
HTML:
<input type="file" name="file[]"/>
<input type="file" name="file[]"/>
<input type="file" name="file[]"/>
PHP:
$file_count = count($_FILES['file']['name']);
for($i=0;$i<$file_count;$i++) {
$file_name = $_FILES['file']['name'][$i];
$file_type = $_FILES['file']['type'][$i];
$file_size = $_FILES['file']['size'][$i];
$file_path = $_FILES['file']['path'][$i];
if($file_name!="" && ($file_type="image/jpeg"||$file_type="image/png"||$file_type="image/gif") && $file_size<=2000000)
if(move_uploaded_file ($file_path, 'pictures_uploaded/' .$file_name))
$query = mysql_query("INSERT INTO `user_input`(keyword, name, categorie, lieu) VALUES ('$keywords', '$name', '$categorie', ' $lieu')");
$query = mysql_query("UPDATE `user_input` set image='pictures_uploaded/$file_name' WHERE `name`='$name'");
if($query == true)
{
echo "file Uploaded";
}
}
} //close the braces accordingly, some seem to be missing in your code
I think it's self-explanatory. It's just looping through your file input array, fetching each file information and processing one at at time.

Categories