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>
';
?>
Related
I searched for some solution and it seems can work by adding some code in it. My codes seems doesn't work. I don't know what to do. I'm new in php. The input type file seems working but the upload button doesn't work and it seems that is the problem of this.
<?php
include ('LoginFunction.php');
$conn = mysqli_connect('localhost','root','','danganan');
$user = $_SESSION['Username'];
$query = "SELECT * FROM tblactivity WHERE Username = '$user'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result);
This is the upload function
if (isset($_POST['upload'])) {
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tem_loc = $_FILES['file']['tmp_name'];
$file_store = "uploads/".$file_name;
if(move_uploaded_file($file_tem_loc, $file_store)) {
echo "Image uploaded!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile info</title>
</head>
<body>
<form method="POST">
<div class="container">
<h1><?php echo "Welcome " . " " . $user; ?></h1>
<img src="<?php $row['Picture']; ?>" width=150; height=150;>
<div class="send-button">
<input type="file" name="file" style="margin-right: -76px;"><br><br>
<input type="submit" name="upload" value="Upload">
<?php
$folder = "uploads/";
if(is_dir($folder)) {
if ($open = opendir($folder)) {
while (($file = readdir($open)) !=false) {
if($file == '.' || $file == '..') continue;
echo '<img src ="uploads/'.$file.'" width = "150" height=150>';
}
closedir($open);
}
}
?>
</div>
<input type="hidden" name="usrid" value="<?php echo $row['ID']; ?>">
<h2>FIRST NAME</h2><input type="text" name="fname" value="<?php echo $row['Fname']; ?>">
<h2>LAST NAME</h2><input type="text" name="lname" value="<?php echo $row['Lname']; ?>">
<h2>USERNAME</h2><input type="text" name="uname" value="<?php echo $row['Username']; ?>">
<h2>PASSWORD</h2><h3><?php echo $row['Password']; ?></h3>
</form>
</body>
</html>
I have a following code where I can upload a single image. This image gets stored in both database and folder. Now what I want is to add multiple images. How can I do that. Help me to come out of this.
<?php
$uploadDir ="C:/wamp/www/dragongym/customers/";
if(isset($_POST['submit']))
{
$intime =DATE("H:i", STRTOTIME($_POST['intime']));
$outtime =DATE("H:i", STRTOTIME($_POST['outtime']));
date_default_timezone_set('Asia/Calcutta');
$today = date("Y-m-d");
$msg="";
$res = "SELECT customer_id FROM customer ORDER by customer_id DESC LIMIT 1";
$qur = mysql_query($res);
while($row = mysql_fetch_array($qur, MYSQL_BOTH))
{
$last_id = $row['customer_id'];
$plus_id = 1;
}
if( $last_id !="")
{
$cust_id = $last_id + $plus_id;
}
$filePath="";
if($_FILES['cimage']['size'] > 0)
{
// echo $cust_id;
// Temporary file name stored on the server for pdf
$filename = basename($_FILES['cimage']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = $cust_id.'.'.$extension;
$tmpName1 = $_FILES['cimage']['tmp_name'];
$fileSize = $_FILES['cimage']['size'];
$fileType = $_FILES['cimage']['type'];
$filePath = $uploadDir . $new;
$resultes = move_uploaded_file($tmpName1, $filePath);
if (!$resultes)
{
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$new = addslashes($new);
$filePath = addslashes($filePath);
}
}
$sql = 'INSERT INTO customer(customer_name,roll_no,customer_number,customer_address,tariff_id,intime,outtime,customer_image,active,joining_date) VALUES("'.$_POST['name'].'","'.$_POST['roll'].'","'.$_POST['number'].'","'.$_POST['address'].'","'.$_POST['tariff'].'","'.$intime.'","'.$outtime.'","'.$filePath.'","1","'.$today.'")';
$msg="<p style=\"color:#99CC00; font-size:13px;\"> Successfully!</p>";
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
}
?>
<form action="#" method="post" enctype="multipart/form-data">
<h2>Registration Form</h2><?php echo $msg; ?>
<label>Name</label>
<input type="text" value="" name="name" id="name" required class="txtfield">
<label>Roll Number</label>
<input type="text" value="" name="roll" id="roll" required class="txtfield">
<label>Mobile Number</label>
<input type="text" value="" name="number" required class="txtfield" id="mobnum">
<label>Address</label>
<textarea name="address" class="txtfield"></textarea>
<label>Upload Photo</label>
<input type="file" value="" name="cimage" class="txtfield">
<!-- <label style="display: block">Timing</label>
<input type="text" value="" name="intime" placeholder="Intime" required class="timefield timepicker">
<input type="text" value="" name="outtime" placeholder="Outtime" required class="timefield timepicker">-->
<input type="submit" value="Save" name="submit" class="btn buttonside1">
</form>
You can use jquery plugin for that..
there is lots of plugin available on google..try this one http://blueimp.github.io/jQuery-File-Upload/
to do multiple file upload you should first have multiple="true" in your tab like so
<input type="file" name='files[]' multiple='true'/>
then use foreach loop to upload files.
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
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.
Im creating a CMS for my site and in my admin page I have an add page that adds new content to my site LOCATED HERE and have added a few form fields.
2 of these are:
IMAGE URL (text box) & UPLOAD IMAGE (select file button)
When I fill in all the fileds and select an image using IMAGE URL and hit add article, it works fine and my form is saved to my database and is then displayed on my site.
When I fill in all the fileds and select an image using UPLOAD IMAGE and hit add article, it adds the image to my selected folder in my cpanel but DOES NOT ADD TO DATABASE.
My question is: How can I get it to add to the database? and save the new images location to the image field on the database?
I have followed this tutorial when adding the upload file button to my page.
Please do not show me links on how to do this as I already have read through them but I stuggle when it comes to adding this to my code.
my add.php code is this.
<?php
session_start();
include_once('../include/connection.php');
if (isset($_SESSION['logged_in'])){
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (!empty($_POST['image']))
{
$image = $_POST['image'];
}
else
{
$image = $_POST['imageupload'];
if (isset($_FILES['imageupload']))
{
$errors = array();
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['imageupload'] ['name'];
$file_ext = strtolower (end (explode ('.', $file_name)));
$file_size = $_FILES['imageupload'] ['size'];
$file_tmp = $_FILES['imageupload'] ['tmp_name'];
if (in_array ($file_ext, $allowed_ext) === false) {
$errors[] = 'File extension not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
if (empty($errors)) {
if (move_uploaded_file($file_tmp, 'images/'.$file_name)) {
echo 'File uploaded';
$image = $file_name;
}
}else{
foreach ($errors as $error)
echo $error, '<br />';
}
}
}
$link = $_POST['link'];
$category = $_POST['category'];
$brand = $_POST['brand'];
if (empty($title) or empty($content)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO mobi (promo_title, promo_content, promo_image, promo_link, promo_cat, promo_name) VALUES(?, ?, ?, ?, ?, ?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $image);
$query->bindValue(4, $link);
$query->bindValue(5, $category);
$query->bindValue(6, $brand);
$query->execute();
header('location: index.php');
}
}
?>
<?php
if (isset($_FILES['Filedata']))
{
// And if it was ok
if ($_FILES['Filedata']['error'] !== UPLOAD_ERR_OK)
exit('Upload failed. Error code: ' . $_FILES['image']['error']);
$filename = $_FILES['Filedata']['name'];
$targetpath = "../img/news/" . $filename; //target directory relative to script location
$copy = copy($_FILES['Filedata']['tmp_name'], $targetpath);
}
?>
<html>
<head>
<title>Add Article</title>
<link rel="stylesheet" href="../other.css" />
</head>
<body>
<div class="container">
<b>← Back</b>
<br />
<div align="center">
<h4>Add Article</h4>
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form action="add.php" method="post" autocomplete="off" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input name="imageupload" type="file" id="image" placeholder="Imageupload" />
<input type="text" name="image" placeholder="Image" /><br /><br />
<input type="link" name="link" placeholder="Link" /><br /><br />
<input type="category" name="category" placeholder="Category" /><br /><br />
<input type="category" name="brand" placeholder="Brand" /><br /><br />
<input type="submit" value="Add Article" />
</form>
</div>
</div>
</body>
</html>
<?php
}else{
header('location: index.php');
}
?>
Please help.
if (move_uploaded_file($file_tmp, 'images/'.$file_name)) {
echo 'File uploaded';
$image = '/images/'.$filename;//try updating the line like this