PHP and MySQLi - Upload Multiple Image - php

I am planning to make an image galary using PHP with MySQL as a database.
I already make a multiple upload images using PHP but I got a problem. When I uploaded 8 images in database only show 1 row data. But in folder there are 8 images that I have upload.
Here is my code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>
<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
{
$filetmp = $_FILES["file_img"]["tmp_name"][$i];
$filename = $_FILES["file_img"]["name"][$i];
$filetype = $_FILES["file_img"]["type"][$i];
$filepath = "uploads/".$filename;
move_uploaded_file($filetmp,$filepath);
$sql = "INSERT INTO files (file,path,type) VALUES ('$filename','$filepath','$filetype')";
if($connect->query($sql) === TRUE) {
header("Location: a.php");
} else {
header("Location: a.php");
}
}
$connect->close();}
?>
</body>
</html>
Can someone help me ? Thanks for ur feedback :)

Move the header location redirect outside the for loop.
Also Refer Upload multiple images and store their path in database.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>
<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
{
$filetmp = $_FILES["file_img"]["tmp_name"][$i];
$filename = $_FILES["file_img"]["name"][$i];
$filetype = $_FILES["file_img"]["type"][$i];
$filepath = "uploads/".$filename;
move_uploaded_file($filetmp,$filepath);
$sql = "INSERT INTO files (`file`,`path`,`type`) VALUES ('$filename','$filepath','$filetype')";
$connect->query($sql);
}
if($connect->query($sql) === TRUE) {
header("Location: a.php");
exit; // always add exit after header Location:
} else {
header("Location: a.php");
exit; // always add exit after header Location:
}
$connect->close();}
?>
</body>
</html>

After some code beautification of your snippet answer became obvious - you only get one new row in database, because in your for loop you redirect user to a.php right after inserting this row.
In other words your for loop will always perform one and only one step.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>
<?php
include_once 'koneksi.php';
if (isset($_POST['btn_upload'])) {
for ($i = 0; $i < count($_FILES['file_img']['name']); $i++) {
$filetmp = $_FILES["file_img"]["tmp_name"][$i];
$filename = $_FILES["file_img"]["name"][$i];
$filetype = $_FILES["file_img"]["type"][$i];
$filepath = "uploads/".$filename;
move_uploaded_file($filetmp, $filepath);
$sql = "INSERT INTO files (file, path, type) VALUES ('$filename','$filepath','$filetype')";
// #NOTICE: Read about SQL Injection and why above SQL is bad.
// #SOLUTION: Place 1
if ($connect->query($sql) === true) {
header("Location: a.php");
exit; // #NOTICE: Always add `exit` after "header Location:"
} else {
header("Location: a.php");
exit; // #NOTICE: Always add `exit` after "header Location:"
}
}
$connect->close();
// #SOLUTION: Place 2
}
?>
</body>
</html>
Can you see it now?
Checkout link below! File [1] is your file after performing some cleaning. It's also contains two comments marked as #SOLUTION. Place 1 is the code you should move to Place 2. After moving you should also change if condition to check if all files were uploaded correctly. File [2] on the other hand is edited by me with (probably) proper solution for your problem.
I hope I helped!
https://github.com/broiniac/stackoverflow/blob/master/44346949/
EDIT: #AdhershMNair:
I think that because of line if($connect->query($sql) === TRUE) { in your solution, data for last uploaded file will be inserted into database twice (once for last iteration in for loop and once for if statement).

Related

i can not upload image php everything is ok but it failes uploading

everything is ok i can seperately insert query into my database but it does not move the uploaded file
here is my code. see please if you can find any issue below.
it checked my image folder directory it is correct the directory takes me to the exact folder.
upload_file is also on in php.ini
but still it is not working.
<?php
$conn = mysqli_connect("localhost", "root", "HERE_IS_MYCORRECT_PASSWORD", "HERE_IS_MYCORRECT_DTABASE_NAME");
if($conn) {
echo "<p style='color:green;'>connected</p>";
}
else {
echo " connection failed";
}
if(isset($_POST['uploadfilesub'])){
$id = $_POST['id'];
$filename = $_FILES['uploadfile']['name'];
$filetmpname = $_FILES['uploadfile']['tmp_name'];
$folder = './Resources/style/images/' . $filename;
echo "<p>".$filename."</p>";
echo "<p>".$filetmpname."</p>";
$sql = "INSERT INTO product_images VALUES ($id,'$filename') ";
if(move_uploaded_file($filetmpname , $folder)){
echo "<p color='green'>moved</p>";
$qry = mysqli_query($conn, $sql);
if($qry){
echo "<p color='green'>Inserted into mysql</p>";
} else {
echo "<p color='red'>Failed to Insert</p>";
}
}
else {
echo "<p style='color:red;'>Failed to move</p>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="id">
<input type="file" name="uploadfile" />
<input type="submit" name="uploadfilesub" value="upload" />
</form>
</body>
</html>
As far as I can see your error (in regards to the particular, mentioned, issue) is very simple:
$folder = './Resources/style/images/';
change to:
$folder = './Resources/style/images/' . $filename;
Simply move_uploaded_file expects full target path and not only target folder.

how to upload the path of an image to Mysql database with android using php files

i want to add an image's path with android to mysql database using a php file. i added the path with a php file to the database but i failed to connect the android app to the php file si i can put the path of the image from android to mysql database can anyone tell me the rignt procedure for doing it ?
this is my php file :
<?php
define('hostname','localhost');
define('user', 'root');
define('password', '');
define('databasename', 'image');
$connect=mysqli_connect(hostname,user,password,databasename);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img" />
<input type="submit" name="btn_upload" value="Upload">
</form>
<?php
if(isset($_POST['btn_upload']))
{
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filepath = "photo/".$filename;
move_uploaded_file($filetmp,$filepath);
$sql = "INSERT INTO img (img_name,img_path,img_type) VALUES ('$filename','$filepath','$filetype')";
$result = mysqli_query($connect,$sql);
}
?>
</body>
</html>

uploading zip files with PHP, undefined index

I'm having issues uploading zip files and can't seem to find an answer.
Index.php
<form id="convertFile" action="convert.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input name="upload" type="file" id="inputFile">
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
convert.php:
if(isset($_FILES)){
echo $_FILES['upload']['name'];
}else{
echo json_encode(array('status'=>'error'));
}
When I upload a zip file, I get: Notice: Undefined index: upload in C:\wamp\www\xmlconverter\convert.php on line 3
This is what chrome shows in the post header:
------WebKitFormBoundaryuFNy5dZtFj7olmD5
Content-Disposition: form-data; name="zip_file"; filename="123.zip"
Content-Type: application/x-zip-compressed
------WebKitFormBoundaryuFNy5dZtFj7olmD5--
This works on any other major file format, but can't get it to read the zip file. If I var_dump $_FILES or $_POST they are empty.
What am I missing? Why does all other files work but zip does not.
Thank you
using wamp and php 5.5.12
Where is your zip file type definition?
Anyways, let say this was the html form to upload zip files you'd have the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
On the server-side script which handles the post you'd have:
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "/home/var/yoursite/httpdocs/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
//if you also wanted to extract the file after upload
//you can do the following
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
I used a script very similar to one posted by #unixmiah without issue on my cPanel based server. Worked great (and has for year now) but ran into issue of error "PHP, undefined index" when using locally with wamp.
Here is the mod that worked for me:
<?php
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if(!empty($_FILES)){
//added above to script and closing } at bottom
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "<b>The file you are trying to upload is not a .zip file! Please try again...</b>";
}
$target_path = "somedir/somesubdir/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("somedir/somesubdir/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "<h2>ZIP file was uploaded and content was replaced!</h2>";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>QikSoft ZIP Upper</title>
</head>
<body>
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label><h3>Upload Your ZIP:</h3> <input type="file" name="zip_file" /></label>
<br /><br />
<input type="submit" name="submit" value="START UPLOAD" />
</form>
</body>
</html>
Also note that the echo message has been changed:
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
One thing that does not work is file restriction. Currently allows other types besides ZIP. Anyone with fix, be greatly appreciated.
It's echo $_FILES['upload']['tmp_name'];
Try checking and adjusting the post_max_size value in your php.ini file, this worked for me as the default is 3M, raised the value to 128M and everything was peachy

Multiple Image insert taking extra one row after each insert

Here I am using this php code for insert multiple images in one field in database table but after insert a row is taking one extra row after each insert .......Help me to solve this issue..
Thank you Advance.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
/*if(isset($_REQUEST['submit']))
{
$pname=$_FILES['image']['name'];
$tmp_name=$_FILES['image']['tmp_name'];
move_uploaded_file($tmp_name."photo/".$pname);
$fileext = pathinfo($pname, "photo/");
$fileext = strtolower($fileext);
}*/
$uploads_dir = 'photo/';
//$images_name ="";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$images_name =$images_name.$name.",";
}
}
$sql=mysql_query("INSERT INTO multiimg(image) values('".$images_name."')");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function addmore(num)
{
if(num==1)
{
document.getElementById('field2').style.display='block';
document.getElementById('ni1').style.display='block';
return false;
}
else if(num==2)
{
document.getElementById('field3').style.display='block';
return false;
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data" name="" action="" method="post">
<div id="field1">Enter One Image :<input type="file" name="image[]" id="img1"/>addmore...</div>
<div id="field2" style="display:none;">Enter Two Image :<input type="file" name="image[]" id="img2"/>add more...</div>
<div id="field3" style="display:none;">Enter Three Image :<input type="file" name="image[]" id="img3"/>addmore...</div>
<div id="field4" style="display:none">Enter Forth Image :<input type="file" name="image[]" id="img4"/>addmore...</div>
<input type="submit" name="submit"/>
</form>
</body>
</html>
please check if the form is posted then do the insert ,else while loading the page a row will be inserted in table with empty data
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
if(isset($_POST['submit'])){
$uploads_dir = 'photo/';
//$images_name ="";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$images_name =$images_name.$name.",";
}
}
$sql=mysql_query("INSERT INTO multiimg(image) values('".$images_name."')");
}
?>

import .csv in mysql script php

i got a PHP script to import a file into my mysql database.
but when i try to use it i get this error:
File not found. Make sure you specified the correct path
but i did not even select a file this is my script:
<?php
include ('db_connect.php');
//connect to the database
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO test (nummer, branche) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
)
");
}
} while ($data = fgetcsv($handle,10000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
any1 who can hlp me with this problem?
Re comment about do/while loop: no, I mean like this
$handle = fopen($file,"r");
if ($handle !== FALSE) {
while (!feof($handle)) {
$data = fgetcsv($handle,10000,",","'");
if ($data[0]) {
mysql_query("INSERT INTO test (nummer, branche) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."'
)
");
}
}
fclose($handle);
}

Categories