How to upload multiple images into PHP and Mysql - php

Hello everyone,
I have a table consist of 10 columns which in 4 of them i want to insert the image paths.
can any one guide me how to insert the image paths into database along with other 6 more columns data in a single query and upload the images into server(inside a folder).
here my html code:
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product full name</label>
<input class="form-control" id="inputdefault" name="name2" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product category</label>
<input class="form-control" id="inputdefault2" name="name1" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product qty</label>
<input class="form-control" id="inputdefault3" name="name3" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 1.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 2.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 3.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 4.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
Here php code :
Note: I did not get image file names in any variable to added into query, everything is working fine here just need to work with images upload and store the path in to database
<?php
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$pname= stripslashes($_REQUEST['name1']);
$pcat= stripslashes($_REQUEST['name2']);
$pprice= stripslashes($_REQUEST['name3']);
$pqty= stripslashes($_REQUEST['qty']);
$pdesc=stripslashes($_REQUEST['description']);
//$spassword=stripslashes($_REQUEST['img']);
$sqlinsert ="INSERT INTO `noorizone`.`products` VALUES ('$pname', '$pcat', '$pprice')";
if($con-> query($sqlinsert)=== true)
{
echo "<center><b style='color:green;'> added successfully... </b>";
echo"</center>";
}
else{
echo "<b style='color:red;'> cant register". $con->error."</b>";
}
}
?>
THANKS IN ADVANCE !!!

This is example for me, you can learn my codes :
$fileImageStatus = ""; // Create your variable for files
if(isset($_FILES['files_status']['name'])){ // Checking value for all input
$fileImageName = array(); // Make an array
for($i = 0; $i < count($_FILES['files_status']['name']); $i++){ // Looping
$imageName = $_FILES['files_status']['name'][$i]; // Give a variable with index from array looped
$uploadPath = '././sistem/users/members/'.$idPenerima.'/unggahan/';
move_uploaded_file($imageTmp, $uploadPath.$imageName); // Path upload
$fileImageName[] = $imageName; // Setting a values from array
}
$fileImageStatus = implode(",", $fileImageName); // Make that values an string
}
// in here you can insert to database with value from $fileImageStatus

I think if you change the name of the file to say file1 instead of file[], you will be fine.
See an example from W3Schools.com
<!DOCTYPE html>
<html>
<body>
<!--
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
-->
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>

Here is a Good tutorial on how to upload multiple images into PHP and Mysql
http://www.wdb24.com/how-to-upload-multiple-images-in-php-and-store-in-mysql/

Related

Upload file Warning: move_uploaded_file(../view/pictureswhy.PNG): failed to open stream: Permission denied

Have been trying to upload an image and it is not working as expected. The error in the title is being displayed on the form. The image is being inserted via a file in the 'View' and checked in the 'Controller', however, when it comes to the final upload it fails, due to permissions I assume...
I have given both files in the view and controller the correct permissions for uploading files - in FileZilla.
The code is:
FORM - View
<form class="article" id="article-form" name="article" method="post" enctype="multipart/form-data">
<ol>
<li>
<label for="heading">Heading</label> <span id="headingMessage"></span>
<input name="heading" id="heading" class="form-control" type="text" required>
</li>
<li>
<label for="topic">Topic</label> <span id="topicMessage" required></span>
<input name="topic" id="topic" class="form-control" type="text" list="football">
<datalist id="football">
<option value="Scotland"></option>
<option value="England"></option>
<option value="Spain"></option>
</datalist>
</li>
<li>
<label for="summary">Summary</label> <span id="summaryMessage"></span>
<input name="summary" id="summary" class="form-control" type="text">
</li>
<li>
<label for="thumbnail">Thumbnail Link</label> <span id="thumbnailMessage"></span>
<!-- <input name="thumbnail" id="thumbnail" class="form-control" type="text" required> -->
<input type="file" name="file" id="file">
</li>
<li>
<label for="video">Video</label> <span id="videoMessage"></span>
<input name="video" id="video" class="form-control" type="text">
</li>
<li>
<label for="articleText">Text</label>
<textarea name="articleText" id="articleText" class="md-textarea form-control" required></textarea>
</li>
<!-- <li>
<div class="g-recaptcha" data-sitekey="6LcUAnQUAAAAAPeF1u6Hcnf0Y5TfS4-0xitZ7ZeZ"></div>
</li> -->
</ol>
<input class="btn btn-success" id="formButton" type="submit" name="submit"value="Submit" name="submit">
<input class="btn btn-danger" id="formButton" type="reset" value="Reset">
</form>
The controller -
//check image
$target_dir = "../view/pictures";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 0;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 2;
//$thumbnail = '<img class="img-responsive" id="articleImage" src="'.$_POST["file"].'">';
echo $target_file;
} else {
echo "File is not an image. <hr>";
$uploadOk = 0;
}
}
$thumbnail=$target_file;
include("../model/api-article.php") ;
if($uploadOk>1)
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
$articleTxt = insertArticle($headline, $topic, $summary, $text, $thumbnail,$video,$date,$userId);
} else {
echo "Sorry, there was an error uploading your file.";
}
}else{
echo "Article not inserted - only upload images (PNG, JPEG)";
}
}
Please excuse the indenting
It's may not enough to give permission to the upload file - you need to permit the whole folder where you are uploading your images.

PHP, using $_FILES and $_POST at the same time but its not working

I am making a admin page to insert all attribute in MySQL and image upload in one folder but getting some error ,Here is code of form
<form role="form" id="form1" action="" enctype="application/x-www-form-urlencoded" method="post">
<div class="col-lg-6">
<div class="form-group">
<label>Title:</label>
<input type="text" name="title" placeholder="enter title" class="form-control"required>
</div>
<div class="form-group">
<div class="col-lg-6 col-md-6 col-sm-6">
<label>Image:</label>
<input type="file" name="upload" id="postimage" class="form-control">
</div>
</div>
<input type="reset" name="reset" value="reset">
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Content:</label>
<input type="text" class="form-control" name="content" placeholder="explain in brief">
</div>
<div class="form-group">
<label>Age:</label>
<input type="text" class="form-control" placeholder="enter require age" name="age">
</div>
<div class="form-group">
<input type="submit" name="submitpost" value="Submit-Post" class="form-control">
</div>
</div>
</form>
and when i am using PHP code for inserting my image in one folder name img and other attributes in MySQL table.
<?php
$target_dir = "../../img/";
if (isset($_FILES['upload'])and isset($_POST['submitpost'])) {
$target_file = $target_dir . basename($_FILES["upload"]["name"]);
if(move_uploaded_file($_FILES["upload"]["tmp_name"], $target_file)){
$title=$_POST['title'];
$age=$_POST['age'];
$content=$_POST['content'];
$query="INSERT INTO `posts`
(`id`,`title`, `image`,`age`, `content`)
VALUES (null,'$title','$target_file','$age','$content')";
if(mysqli_query($con,$query))
{
echo "<script>alert('passed')</script>";
}else{
echo "<script>alert('not passed')</script>";
}
}else{
echo "<script>alert('problem with image upload')</script>";}
}
?>
But after submitting i am getting nothing, neither error or any notice nothing ,i don't know what is problem help me and I did try some other code then its inserting in table but image does not uploading in target folder .Help me through it i am new in PHP , so
You have added enctype="application/x-www-form-urlencoded" in the form for file input, its wrong. add like below
<form role="form" id="form1" action="" enctype="multipart/form-data" method="post">
Add PHP code like
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/img/';
if(!empty($_FILES['upload']['name'] && isset($_POST['submitpost']))){
$target_file = $target_dir . basename($_FILES["upload"]["name"]);
if(move_uploaded_file($_FILES["upload"]["tmp_name"], $target_file)){
extract($_POST);
$title = mysqli_real_escape_string($con,$title);
$age = mysqli_real_escape_string($con,$age);
$content = mysqli_real_escape_string($con,$content);
$query = "INSERT INTO `posts` (`id`,`title`,`image`,`age`,`content`)
VALUES (null,'{$title}','{$target_file}','{$age}','{$content}');";
if(mysqli_query($con,$query)){
echo "<script>alert('passed')</script>";
}else{
echo "<script>alert('not passed')</script>";
}
}else{
echo "<script>alert('problem with image upload')</script>";
}
}
please make sure $target_dir is correct path of your image upload directory.

Image cannot upload on server using html5 form

I have html form which i used to upload image from mobile camera to server. code like below :
<form method="post" action="addpreview.php" name="formregister" enctype="multipart/form-data">
<div class="field half first">
<label for="name">Make Your Title</label>
<input type="text" name="title" id="title" />
</div>
<div class="field half">
<label for="email">Promoted By Text</label>
<input type="text" name="promoted" id="promoted" />
</div>
<ul class="actions">
<li>
<input type="file" name="photo" accept="image/*" capture="camera" style="" class="special fit" />
</li>
</ul>
<ul class="actions">
<center>
<li>
<input type="submit" name="Submit" value="Let's Preview" class="special" />
</li>
</center>
</ul>
Then below is code for upload processing in addpreview.php
if(isset($_POST['Submit'])) {
$title = $viral->escape_string($_POST['title']);
$promoted = $viral->escape_string($_POST['promoted']);
// upload image
if (($_FILES['photo']['name']!="")){
// Where the file is going to be stored
$target_dir = "upload/";
$file = $_FILES['photo']['name'];
$path = pathinfo($file);
$filename = $path['filename'];
$ext = $path['extension'];
$temp_name = $_FILES['photo']['tmp_name'];
$path_filename_ext = $target_dir.$filename.".".$ext;
// Check if file already exists
if (file_exists($path_filename_ext)) {
echo "Sorry, file already exists.";
}else{
move_uploaded_file($temp_name,$path_filename_ext);
echo "Congratulations! File Uploaded Successfully.";
}
}
}
It's work when i upload file using image from desktop. but upload failed when i tried upload using mobile camera.
Any missing code on mine ?

How to ulpload multiple images in one time using php form?

Here, my php script for upload image in server. i want user can upload multiple images on one records. right now, in this code at time only one image can post, user's requirement is they can post multiple images at time. I don't idea how can I possible using arrays. please help. Thanks in advance :)
<?php
include ("connect.php");
if(isset($_POST['submit']))
{
$event = $_POST['evnt_name'];
$image_name = $_FILES['evnt_img']['name'];
$image_type = $_FILES['evnt_img']['type'];
$image_size = $_FILES['evnt_img']['size'];
$image_tmp = $_FILES['evnt_img']['tmp_name'];
if($event=='' && $image_name==''){
echo "<script>alert('Any field is empty')</script>";
exit();
}
if($image_type=="image/jpeg" OR $image_type=="image/png" OR $image_type=="image/gif")
{
if($image_size<=50000)
{
move_uploaded_file($image_tmp,"imagess/$image_name");
}
else
{
echo "<script>alert('image is large, only 50kb size allowed')</script>";
exit();
}
}
else{
echo "<script>alert('image type is invalid')</script>";
exit();
}
$query = "insert into event_update (evnt_text,evnt_img) values ('$event','$image_name')";
if(mysqli_query($conn,$query))
{
echo "<script>alert('Post has been published')</script>";
exit();
}
}
?>
And below my simple bootstrap HTML code for form
<div class="col-lg-12">
<form method="POST" action="evntform.php" enctype="multipart/form-data">
<div class="form-group">
<label>Events Name</label>
<input type="text" name="evnt_name" placeholder="Write Events Name" class="form-control">
</div>
<div class="form-group">
<label>File input</label>
<input type="file" name="evnt_img[]">
</div>
<button name="submit" type="submit" class="btn btn-default">Submit Button</button>
</form>
</div>
Here is a quick example:
HTML:
<div class="col-lg-12">
<form method="POST" action="evntform.php" enctype="multipart/form-data">
<div class="form-group">
<label>Events Name</label>
<input type="text" name="evnt_name" placeholder="Write Events Name" class="form-control">
</div>
<div class="form-group">
<label>File input</label>
<input type="file" name="evnt_img[]" multiple>
</div>
<button name="submit" type="submit" class="btn btn-default">Submit Button</button>
</form>
PHP code to select the first image uploaded:
<?php
include ("connect.php");
if(isset($_POST['submit']))
{
$event = $_POST['evnt_name'];
$image_name = $_FILES['evnt_img'][0]['name'];
$image_type = $_FILES['evnt_img'][0]['type'];
$image_size = $_FILES['evnt_img'][0]['size'];
$image_tmp = $_FILES['evnt_img'][0]['tmp_name'];
....
You can use a for loop for every image:
for($i=0;$i<count($_FILES['evnt_img']);$i++){
$image_name = $_FILES['evnt_img'][$i]['name'];
}
J

image update cannot takeplace

I am trying to upload image to the database by update query using php file upload where database already contain a file Here is my code, problem is I doesnot get the new file.
if (isset($_POST["events"]) && isset($_POST["description"]))
{
$id = $_POST["id"];
$title = $_POST["events"];
$_POST["description"] = trim($_POST["description"]);
$description = $_POST["description"];
if(isset($_POST['images']) && !empty($_POST['images']))
{
$filetmp = $_FILES["images"]["tmp_name"];
$filename = $_FILES["images"]["name"];
$filetype = $_FILES["images"]["type"];
$filepath = "photo2/".$filename;
move_uploaded_file($filetmp,$filepath);
}
else
{
$filepath = $_POST['old_image_path'];
}
$update1 = update_query($title,$description,$filepath,$id);
if($update1)
{
header("location:hotel1_galery_event.php?msg=Update Sucess");
}
}
HTML Code Preview
<form action="hotel1_galery_eventedit.php" method="post" class="col-sm-4" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $val->event_id;?>">
<div class="form-group has-info">
<label class="control-label" for="inputSuccess">Event title</label>
<input type="text" class="form-control" name="events" value="">
</div>
<div class="form-group has-info">
<label class="control-label" >Event Description</label>
<textarea name="description" class="form-control text-left" rows="3">
</textarea>
</div>
<div class="form-group has-info">
<label>Event Related images</label>
<input type="hidden" name="old_image_path" value="<?php echo $val->image_path?>">
<input type="file" name="images" value="something">
</div>
<button type="submit" class="btn btn-primary">
<span>UPDATE</span>
</button>
</form>
input type='file' POST you file in $_FILES
SO instead of this
if(isset($_POST['images']) && !empty($_POST['images']))
You have to check your condition as
if (!empty($_FILES['images']['name'])) {
$filetmp = $_FILES["images"]["tmp_name"];
$filename = $_FILES["images"]["name"];
$filetype = $_FILES["images"]["type"];
$filepath = "photo2/" . $filename;
move_uploaded_file($filetmp, $filepath);
}

Categories