MySQL insert stmt wont loop in file upload foreach loop - php

The code uploads the files and is supposed to submit the file path to the database so I can use the file paths elsewhere.
All the files upload fine in the loop, but for some reason, after it successfully submits the first MySQL stmt insert, it somehow bypasses the inserts that come after when it goes through the loop again, to upload the next file in the $_FILES[] superglobal
Here is the markup for the form
<?php
session_start();
include 'includes/functions.php';
drawHeader();
echo'
<div class="main_content_container">
';
if ( isset($_SESSION['userId'])) {
$amz_numb = $_GET['amz_numb'];
echo'
<form action="http://Localhost/Tierrashop.ca/includes/upload.php"
method="post" enctype="multipart/form-data">
Send these files
<input name="amz_numb" type="hidden"
value="'. $amz_numb .'"/><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<button type="file">Upload Files</button>
</form>
<a href="http://localhost/Tierrashop.ca/content_upload.php">
<button>Go back to product details... </button></a>
';
} else {
echo '';
}
//close of main content div
echo '</div>';
drawFooter();
?>
PHP file that launches upon form submission
<?php
include 'config.php';
if (isset($_POST['amz_numb'])) {
$uploadlocation = "../product_images/";
$amz_numb = $_POST['amz_numb'];
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for ($i = 0; $i < $countfiles; $i++) {
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i], $uploadlocation . $filename);
$directory_location = $uploadlocation . basename($filename);
chmod($directory_location, 0644);
//insert amz numb and path into db
$stmt = mysqli_prepare($conn, "INSERT INTO images ( amz_product_code, filepath )
VALUES (?,?)");
mysqli_stmt_bind_param($stmt, 'ss', $amz_numb, $directory_location);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
}

Take a look at this please:
https://www.php.net/manual/en/mysqli-stmt.close.php
The user contributed note might be helpful for your case:
"if you are repeating an statement in an loop using bind_param and so on inside it for a larger operation. i thougt id would be good to clean it with stmt->close. but it broke always with an error after aprox. 250 operations . As i tried it with stmt->reset it worked for me."
This might be the better option: https://www.php.net/manual/de/mysqli-stmt.reset.php
Or - much better - use PDO!
UPDATE: More on PDO
If you don't know how to use the more modern standard "PDO" (if I recall it correctly it stands for "PHP Data Objects") this should be really helpful. I used this myself to make my own database handler.
https://culttt.com/2012/10/01/roll-your-own-pdo-php-class/
The only caveat: The link above is a bit US centric. If you use it like that you will be in trouble if you support other languages in addition to English(US).
In //Define Configuration you should add:
define("DB_CHARSET", "utf8mb4");
Then in the database class itself you should add:
private $charset = DB_CHARSET;
"Set DSN" should consequently be modified like this:
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ';charset=' . $this->charset;
Apart from these minor changes the example is still very useful.

Yaaaaa, none of that resetting stuff helped.
Figured out you don't have to keep preparing the statement, however not sure if that's what was stopping it.
I had it uploading the file, than was preparing the stmt to then execute.
In the php.ini file I had:
max_file_uploads = 3, which explained why only three files were getting inserted and locking up the script in the loop.
Also I changed post_max_size = 150mb thinking that this allows all those files to be stored in the tmp_name key in the $_FILES superglobal

Related

how to count number of uploaded files in php

How can i count the number of uploaded files?
This is my form:
<div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Images Here</h1>
</div>
<form id="sfmFiler" class="sfmform" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple />
<input type="submit" name="submitHandler" id="submitHandler" class="buttonUpload" value="Upload">
</form>
and this is the piece of php which uploads the files:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$tmpFilePath = $_FILES['file']['tmp_name'];
$newFilePath = $dir.'/' . $_FILES['file']['name'];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "xxx files are successfully uploaded";
}
}
In this code you are getting only one file thats why you are getting count result 1. if change your input file name like "file[]"
<input type="file" name="file[]" id="file" multiple />
and then use the below line code you will get your desire result. Cause its needs an array filed to hold the input data.
<?php echo count($_FILES['file']['name']); ?>
Thanks, i tried in my system get the result.
AFriend is correct. The above answers always return 1.
Try:
echo count(array_filter($_FILES['file']['name']))
Worked for me anyway.
_t
Using the array_filter function it works
try
$countfiles = count(array_filter($_FILES['file']['name']));
It returns 0 in case of NULL, 1 in case of 1 file uploaded, etc.
Check this answer
<?php echo count($_FILES['file']['name']); ?>
php multiple file uploads get the exact count of files a user uploaded and not the count of all input fields in the array
You could use the count function:
$no_files = count($_FILES);
If no files are selected and your file count is 1, you can use this line before moving the file:
if (!empty($_FILES['file']['tmp_name'][0])) {
for($i=0;$i<$countfiles;$i++){

Upload images to MySQL PHP

I'm trying to upload images to mysql, when i try with this code, it seems like it only insert databse, but no image filename uploaded to my server, can i know what went wrong
<form method="post" action="">
<?php
include ("setting/connect.php");
$g = mysql_query("select max(id) from abc");
while($id=mysql_fetch_array($g))
{
?>
<input type="text" name="id" value="<?php echo $id[0]+1; ?>" hidden/>
<?php }
?>
<div class="form-group">
<label>Image</label>
<input name="image" type="file">
</div>
<div class="form-group input-group">
<span class="input-group-addon">Title</span>
<input name="title" type="text" class="form-control" placeholder="">
</div>
<center><input class="btn btn-primary" type="submit" name="cmdadd" value="ADD" />
<button type="button" class="btn btn-danger">BACK</button></center>
</div>
<!-- /.panel-body -->
</form>
My php:
<?php
$id = $_POST['id'];
$title= trim($_POST['title']);
$path = "uploads/";
$tmp_name = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
if(isset($_POST['cmdadd'])){
if(empty($id)||empty($title))
{
echo "<center>Error!</center>";
}
if($_FILES["image"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else{
move_uploaded_file($tmp_name,$path.$name);
$file="uploads/".$name;
include "setting/connect.php";
mysql_query("SET NAMES 'UTF8'");
$i = mysql_query("insert into abc values ('".$id."','".$file."','".$title."')");
if($i==true){
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=danhsachtindang.php">';
}
//if($i==true){
//header('Location:index.php');
//exit;
//mysql_close();
//}
}
}
?>
Result from this: when i try to upload eg, picture.jpg, in the mysql table, it only came out "avatars/" on the column and HAVEN'T ANYTHING UPLOADED TO SERVER.
Your form lacks enctype="multipart/form-data" it's required when uploading files.
Modify it to read as:
<form method="post" action="" enctype="multipart/form-data">
Consult the manual: http://php.net/manual/en/function.move-uploaded-file.php
Also make sure that the folder has proper permissions set to write to.
Consult chmod on PHP.net for more information on setting folder/files permissions.
Sidenote #1:
Since you're using $path = "uploads/"; am assuming that you are running your code from the root of your server.
If this isn't the case, you will need to adjust it accordingly.
I.e.: $path = "../uploads/"; depending on the location of your file's execution.
Just an insight.
Sidenote #2:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
it only came out "avatars/" on the column and HAVEN'T ANYTHING UPLOADED TO SERVER
Are you trying to upload to avatars/ or uploads/?
Check that.

PHP cannot upload multiple images

I have a form in which I want to upload at most five images. The name and extension of the images are supposed to be inserted in the database table 'images' and then uploaded to the _uploads/name_of_the_album/ directory.
The problem is, when I choose some images and hit upload, only the first image is uploaded correctly, the other images fail.
Here is my code:
if(isset($_FILES['image']) === true){
$files = $_FILES['image'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$album_id = (int)$_GET['album_id'];
$album_name = $_GET['album_name'];
for($i=0; $i<count($files['name']); $i++){
$name = $files['name'][$i];
$tmp_name = $files['tmp_name'][$i];
$size = $files['size'][$i];
$ext = explode('.', $files['name'][$i]);
$ext = strtolower(end($ext));
$img_name = explode('.', $files['name'][$i]);
$img_name = strtolower(current($img_name));
//do some testing echos to see the result
//echo $img_name."<br>";
//here i'm going to add some validation as soon as
// i fix the multi-upload problem
//insert image into database
$query_insert_image = "INSERT INTO `images` (album_id, image_name, image_ext) VALUES ({$album_id}, '{$img_name}', '{$ext}') ";
$insert_image = mysql_query($query_insert_image, $connection) or die(mysql_error());
if(mysql_affected_rows() == 1){
move_uploaded_file($tmp_name, '../_uploads/'.$album_name.'/'.$name);
}
//redirect
redirect_to("view_album.php?succeed=1");
}//end the for loop
//echo '<pre>',print_r($files, true),'</pre>';
}
And here is some of the code of the form:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" />
</p>
......
Any ideas what I'm doing wrong?
I think you're cutting the branch from under your own feet.
redirect_to("view_album.php?succeed=1");
Redirecting means refreshing the page which means the end of execution. When that redirect is triggered after the first for loop ends and first image is uploaded the for will not continue to the next iteration.
And the fix of course is to push that line after the for loop (and never expect anything after a redirect to ever execute - unless the headers are already sent).
Most functions that do what redirect_to() does (it's not a core function it's based on another function header()) also make sure execution stops (have a line calling header() and another line calling die()/exit()).
try this php code ,working for me:
for($i=1;$i<6;$i++)
{
if(!empty($_FILES['image_upload'.$i])):
$target = "images/".$_FILES['image_upload'.$i]['name'];
$image_upload.= ",".mysql_real_escape_string(($_FILES['image_upload'.$i]['name']));
move_uploaded_file($_FILES['image_upload'.$i]['tmp_name'], $target);
endif;
}
create a folder in your root named "images" ,all the images will be moved in this folder.
html form may be looks like:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image_upload1" id="image_upload1" /><br />
<input type="file" name="image_upload2" id="image_upload2" /><br />
<input type="file" name="image_upload3" id="image_upload3" /><br />
<input type="file" name="image_upload4" id="image_upload4" /><br />
<input type="file" name="image_upload5" id="image_upload5" />
</p>
......
this code is running on my end ,and after some editing as according to your needs may be useful for you.
Happy coding!
foreach($_POST['image'] as $report_id){
$sql="INSERT INTO images (album_id, image_name, image_ext) VALUES ('{$album_id}', '{$report_id}', '{$ext}') ";
$queryExe=mysql_query($sql);
}
replace this code in the place of your code after "//insert image into database" .
http://php.net/manual/en/features.file-upload.multiple.php
Read the Warning block 'Since PHP 5.2.12, the max_file_uploads configuration...'. Maybe that's the problem.
And there are some good examples and maybe You should use foreach instead of for.
1) Create a .htaccess file in the root folder of web server.
2) Put the following code in side the .htaccess file and save it.
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200
Now you can upload the file-size up-to 20MB in a simple way using file field in your html form and move_uploaded_file() function available in PHP.

var_dump not returning a value

I want to allow a user the upload an image (file) for their profile picture, on my website. They upload the image via an HTML form, but I am having trouble moving the file to the folder I want it to. I don't want to mess with the php.ini file to change the upload path. I want to use move_uploaded_file(). I try and use $tmp= $_FILES['picture']['tmp_name'] and var_dump($tmp), but It keeps returning a value of (0). So, I think the problem has something to do with that. Here is my code,
Here is my HTML:
<form enctype="multipart/form-data" method="post" action="upload_img.php">
<input type="hidden" name="MAX_FILE_SIZE" value="32768"/>
<input type="text" name="name" value=""/>
<input type="file" name="picture" value="picture"/>
<input type="submit" name="submit" value="upload"/>
</form>
And my PHP:
<?php
define('GW_UPLOADPATH', 'images/');
$picture= $_FILES['picture']['name'];
$name= $_POST['name'];
$tmp= $_FILES['picture']['tmp_name'];
var_dump($picture);
var_dump($name);
var_dump($tmp);
$connect= mysqli_connect(//connect params)
or die('error connecting with the database');
$query= "INSERT INTO pics (pic, name) VALUES ('$picture', '$name')";
$target= GW_UPLOADPATH . $picture ;
if (move_uploaded_file($_FILES['picture']['tmp_name'], $target);))
{
mysqli_query($connect, $query)
or die('error with query');
}
?>
Your issue likely has something to do with php's upload_max_filesize and post_max_size. Check those 2 settings in your php.ini and make sure the file you are trying to upload isn't larger than either of them.

Upload multiple text files into MySQL

I have ZERO experience coding uploading files through browser, so this part is all very new to me.
I need to give users (in fact they will be only one or two authorized users) a way to upload multiple text files (think 50-200 files) directly into a MYSQL database.
I don't want to give them FTP access, but am OK allowing them to enter files into the database.
I can figure out how to get the data from a PHP array into the MYSQL database.
What I can't figure out is how to get the contents of multiple files into the PHP array(s).
Please help out with the code.
This example should help you understand the basic idea
<?php
$fileContents = Array();
if(count($_FILES) != 0){
foreach($_FILES as $file){
$fp = fopen($file["tmp_name"], "r");
array_push($fileContents, fread($fp, $file["size"]));
fclose($fp);
}
//$fileContents now holds all of the text of every file uploaded
}
?>
<html>
<head>
</head>
<body>
<form action="test.php" method="post" enctype="multipart/form-data">
<input type="file" name="file1" id="file" />
<input type="file" name="file2" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
It first checks that there has been files posted to itself.
If there is files, it loops through each and opens them while they are in their temporary file state.
After that it reads all of the contents at once (be careful with this) using the size attribute that sent with it.
At the same time, it is pushing the contents into the array called $fileContents.
So $fileContents[0] holds the first text file and so on.
Just add more <input type="file">s to your page, and they will all appear in the $_FILES array, which you can loop to retrieve them.
However:
The structure of the $_FILES array is slightly illogical when it comes to multiple files - make sure you read the manual carefully, it is a little counter intuitive.
Make sure that your upload_max_filesize, post_max_size, max_file_uploads and max_input_time PHP.ini directives are generous enough.
See also: Handling multiple file uploads in PHP.
<!-- FORM -->
<form method="post" enctype="multipart/form-data">
<?php
for($i=1;$i<=10;$i++) //change 10 to any number for more upload fields
{
echo '<input type="file" name="files[]" /><br />';
}
?>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
//Processor
if(isset($_POST['submit']))
{
foreach($_FILES['files']['tmp_name'] as $tmp_name)
{
if(!empty($tmp_name))
{
$filecontent[] = file_get_contents($tmp_name);
}
}
//Test
echo '<pre>';
print_r($filecontent);
echo '</pre>';
}
?>
Thank you everyone who has contributed to this. I am having a very hard time choosing the answer, because I think it's a 50/50 effort by John and DaveRandom.
In case someone wants to see the end product here it is:
HTML:
<html>
<head>
</head>
<body>
<form method="post" action="test.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
PHP:
<?php
function rearrange( $arr ){
foreach( $arr as $key => $all ){
foreach( $all as $i => $val ){
$new[$i][$key] = $val;
}
}
return $new;
}
$fileContents = Array();
if(count($_FILES['filesToUpload'])) {
$realfiles=rearrange($_FILES['filesToUpload']);
foreach ($realfiles as $file) {
$fp = fopen($file["tmp_name"], "r");
array_push($fileContents, fread($fp, $file["size"]));
fclose($fp);
}
foreach ($fileContents as $thisone) {
echo "<textarea wrap='off'>\n";
echo $thisone;
echo "</textarea>\n";
echo "<br>----<br>";
}
}
?>

Categories