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

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

Related

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.

In Wordpress, how to code a custom form with file upload option and save the records in MySql?

So far I have been able to make a custom form which upon successful entry save the value to a MySql table called "form_entry"
Below is the code for a form:
<form method="post" class="container">
<div class="row">
<div class="col-md-6 mb-3">
<label>Name</label>
<input type="text" name="myname" class="form-control" placeholder="Name" value="John Doe" required>
</div>
<div class="col-md-3 mb-3">
<label>State</label>
<input type="text" name="statename" class="form-control" placeholder="State" required>
</div>
</div>
<button class="btn btn-primary" type="submit" name="BtnSubmit" value="submit">Submit form</button>
</form>
And I insert a few codes in the functions.php under my template folder like this :
if(isset($_POST['BtnSubmit'])) {
global $wpdb;
$data_array = array(
'myname' => $_POST['myname'],
'statename' => $_POST['statename'],
);
$table_name = 'form_entry';
$rowResult = $wpdb ->insert($table_name, $data_array, $format=NULL);
if($rowResult == 1) {
echo 'Success';
}
else {
echo ' Error in my pant';
}
die;
}
This is working fine. But I want to add a file upload option in the form and save the uploaded file location to MySql. Please help.
You have to add one field into your html form. and add parameter for into form.
<form method="post" class="container" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6 mb-3">
<label>File</label>
<input type="file" name="myfile" class="form-control" required/>
</div>
</div>
then after submit you have to save uploaded file at particular location and save that file into your db.
if (isset($_POST['BtnSubmit'])) {
$target = 'uploads/' . basename($_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target)) {
$fp = fopen($target, "r");
}
global $wpdb;
$data_array = array(
'myname' => $_POST['myname'],
'statename' => $_POST['statename'],
'filename' => $target
);
}
I think it will work for you !! feel free to ask me.

How to upload multiple images into PHP and Mysql

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/

how to add either a link or file with codeigniter

I have two fields one for link and one for file upload in form, how do i add only one of those i.e. either link or file in database,
Sorry for any wrong code and methods, I am a newbie here and this is my first question in stack overflow. Hope you all help me out.
My Controller is
public function add_scrolllink()
{
$this->form_validation->set_rules('stitle','File Title','trim|required');
$this->form_validation->set_rules('slink','File Link','trim|required');
if(empty($_FILES['sfile']['name']))
{
$this->form_validation->set_rules('slink','File Link','required');
}
if($this->form_validation->run() == FALSE)
{
$this->load->view("add_scrolllink");
}
else
{
$slink_id = $this->input->post('stitle');
$slink_files = $this->input->post('slink');
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'pdf|docx|doc';
$config['max_size'] = 9000;
$this->upload->initialize($config);
$this->load->library('upload',$config);
if(!$this->upload->do_upload('slink'))
{
$msg1 = $this->upload->display_errors();
header("Location:".base_url()."news/add_scrolllink?msg1=$msg1");
}
else
{
$output = $this->upload->data();
$file2 = $output['file_name'];
$this->load->model('mpages');
$output1 = $this->mpages->add_scrolllink($slink_title,$file2);
if($output1)
{
$msg = "Scrolling Link added successfully!";
header("Location:".base_url()."news/scrolllink_list?
msg=$msg");
}
else
{
$msg1 = 'Scrolling Link add failed. Try again!';
header("Location:".base_url()."news/add_scrolllink?
msg1=$msg1");
}
}
}
//My View is
<form action="<?php echo base_url(); ?>news/add_scrolllink" method="post"
role="form" enctype="multipart/form-data">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<label>Scrolling Link Title</label>
<input type="text" name="stitle" class="form-
control" value="<?php echo set_value('stitle'); ?>" placeholder="Enter
Scrolling Link Title">
</div>
<style type="text/css">
p.help-block{color:#ff0000;}
</style>
<div class="form-group">
<label>Scrolling Link</label>
<input type="text" name="slink" class="form-control"
value="<?php echo set_value('slink'); ?>" placeholder="Enter Scrolling
Link">
</div>
OR ADD FILE TO SCROLL LINK
<div class="form-group">
<label>Choose File to Upload</label>
<input type="file" name="slink" class="form-
control">
</div>
<input type="submit" name="submit" class="btn btn-
primary" value="Add Link"><br>
<?php echo "<br><span
style='color:#ff0000;'>".validation_errors()."</span>"; ?>
<?php
if(isset($_GET['msg'])){
echo "<div class='alert alert-success
fadein'>".$_GET['msg']."</div>";
}
if(isset($_GET['msg1'])){
echo "<div class='alert alert-danger
fadein'>".$_GET['msg1']."</div>";
}
?>
</div>
</div>
</div>
<div class="col-md-2"></div>
<div class="clearfix"></div>
</div>
</form>
you have use jquery to get input box value using this code and set some condition
$('#slink-id').val(); // set link field input box id
$('#slinkFile-id').val(); //set upload file field id
if($('#slink-id').val() != '' && $('#slinkFile-id').val() == ''){
// setread only your file field
}else{
// set read only link field
}

Update query is not working in Mysql but instead inserting new data in this query

Table name = image_2017.My image is not updating by this UPDATE query in a particular $_GET['id'] instead image is inserting as a new image. I don't know what is wrong in this code.I am new to php. Kindly help me someone.
<?php
include_once "config.php";
session_start();
if(!isset($_SESSION)){
header("index.php");
}
$id = $_GET['id'];
//echo $id;
if(!empty($_FILES)){
$t = time();
$filename = $category."_".$t."_".$_FILES['image']['name'];
$upload = "uploads/";
$fileupload = move_uploaded_file($_FILES['image']['tmp_name'],$upload.$filename);
if($fileupload){
$msg1 = "File uploaded Successfully";
}else{
$msg2 = "File uploaded Failed";
}
}
if(!empty($_POST)){
$category = $_POST['category'];
$image = $_FILES['image'];
$query = "UPDATE image_2017 SET category ='$category', image ='$filename' WHERE id ='$id' ";
$result = $db->query($query);
if($result){
$msg3 = "Image Updated Successfully";
}else{
$msg4 = "Image not Updated";
}
}else{
//echo "Please enter all the details";
}
?>
<html>
<body>
<form class="form news" style="padding:10px;" method="post" action="image-2017.php" enctype="multipart/form-data">
<div class="row">
<div class="form-group">
<label class="control-label col-md-2">category</label>
<div class="col-md-4">
<select class="form-control" name="category">
<option>--> Select <--</option>
<option>Birthday</option>
<option>Christmas</option>
<option>Fruits</option>
<option>Ganesh Chathurthi</option>
<option>Green Day</option>
<option>Guitar Play</option>
<option>Independence Day</option>
<option>Krishna Jayanthi</option>
<option>Onam</option>
<option>Splash Pool</option>
<option>Teddy Bear</option>
<option>Veg Market</option>
<option>Vijayadhasami</option>
</select>
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-group">
<label class="control-label col-md-2">Upload Image</label>
<div class="col-md-10">
<input type="file" name="image">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-10">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-primary">Back</button>
</div>
</div>
</form>
</body>
</html>
I updated html to add a post for id
<?php
include_once "config.php";
session_start();
if(!isset($_SESSION)){
header("index.php");
}
$id = $_POST['id'];
//echo $id;
if(!empty($_FILES)){
$t = time();
$filename = $category."_".$t."_".$_FILES['image']['name'];
$upload = "uploads/";
$fileupload = move_uploaded_file($_FILES['image']['tmp_name'],$upload.$filename);
if($fileupload){
$msg1 = "File uploaded Successfully";
}else{
$msg2 = "File uploaded Failed";
}
}
if(!empty($_POST)){
$category = $_POST['category'];
$image = $_FILES['image'];
$query = "UPDATE image_2017 SET category ='$category', image ='$filename' WHERE id ='$id' ";
$result = $db->query($query);
if($result){
$msg3 = "Image Updated Successfully";
}else{
$msg4 = "Image not Updated";
}
}else{
//echo "Please enter all the details";
}
?>
<html>
<body>
<form class="form news" style="padding:10px;" method="post" action="image-2017.php" enctype="multipart/form-data">
<div class="row">
<div class="form-group">
<label class="control-label col-md-2">category</label>
<div class="col-md-4">
<select class="form-control" name="category">
<option>--> Select <--</option>
<option>Birthday</option>
<option>Christmas</option>
<option>Fruits</option>
<option>Ganesh Chathurthi</option>
<option>Green Day</option>
<option>Guitar Play</option>
<option>Independence Day</option>
<option>Krishna Jayanthi</option>
<option>Onam</option>
<option>Splash Pool</option>
<option>Teddy Bear</option>
<option>Veg Market</option>
<option>Vijayadhasami</option>
</select>
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-group">
<label class="control-label col-md-2">Upload Image</label>
<div class="col-md-10">
<input type="file" name="image">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-10">
<input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-primary">Back</button>
</div>
</div>
</form>
</body>
</html>
Make sure you reach the page as: mypage.php?id=12

Categories