multiple file upload sql/php - php

i am trying to upload multiple files and then insert the files names in mysql db
my problem is with inserting the names it only store the last file name
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
}
}
notice that all the files are uploaded successfully

for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
}
}
you are just creating a string and storing some value. you have not executed it ..
Say $str = "apple"; Its just a declaration. I presume you have executed the query after the loop. Say you have 10 files. loop gets executed 10 times and $na has the last filename which gets inserted.
Soln: move your execute query inside the for loop.
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
mysql_query($con,$sql); // note: $con is your connection string
}
}

Related

php, upload multiple files from multiple input

I have a form with multiple rows (rows from SQL, iterated and generated the form).
Each of those rows has a multiple file input field (the user can upload 0, 1 or multiple in each input).
Files are being uploaded correctly, with correctly assigned new file names (file names are generated based on each row SQL ID).
Then after user click the SUBMIT, the file names are added to a column in SQL table.
The form can generate 0, 1 ... 100 rows, so to prevent the php iterating through all those 100s rows, and executing an UPDATE or rows where it is not needed, I only execute the UPDATE on rows that the user has touched.
My problem is when I upload a single or multiple file on a singular file input field (a row), then everything works as expected.
However, when I try to upload 1 or more files in separate file inputs fields, then something strange happens in SQL, the files upload to the server are all OK, but database goes weird.
The first input (row) will have correct number of files with correct names, as desired.
Every next input (row, in the database after the UPDATE) will have the all the file names from all previous inputs, plus the ones that were uploaded for the specific input... if that makes sense... Here illustration:
Input 1: input1file1.jpg, input1file2.jpg
Input 2: input1file1.jpg, input1file2.jpg, input2file1.jpg
Because each input field can take multiple files, so the input name is already an array name='attachment[]'.
To distinguish between those input fields, I add row ID to file name.
Here is my code, I cannot work out what is causing it?
Form:
<form enctype="multipart/form-data" method="post">
...
php iteration:
<div>
<input class="hasChanged" name="attachments'.$row['pk'].'[]" type="file" multiple>
<input value="'.$row['existing_attachments'].'" id="updateAttachmentValue'.$row['pk'].'" name="existingAttachments'.$row['pk'].'">
</div>
...
</form>
PHP:
//iterate
foreach($_POST['foo_field'] as $key => $n){
if(in_array($upl[$key], $touched_rows)){
$aID = $upl[$key];
$prevAttachments = (empty($_POST['existingAttachments'.$aID]) || $_POST['existingAttachments'.$aID]=='|') ? NULL : $_POST['existingAttachments'.$aID];
$attachments = NULL;
if(count($_FILES['attachments'.$aID]['name']) > 0){
if(!empty($_FILES['attachments'.$aID])){
for($i=0; $i<count($_FILES['attachments'.$aID]['name']); $i++){//Loop through each file
$tmpFilePath = $_FILES['attachments'.$aID]['tmp_name'][$i];//Get the temp file path
if($tmpFilePath != ''){//Make sure we have a filepath
$shortname = 'AP-'.$aID.'-'.$_FILES['attachments'.$aID]['name'][$i];//save the filename
$filePath = $attachmentDirectory.'\AP-'.$aID.'-'.$_FILES['attachments'.$aID]['name'][$i];//save the url and the file
if(move_uploaded_file($tmpFilePath, $filePath)){//Upload the file into the correct dir
$files[] = $shortname;
}
$attachments = implode('|',$files);
}
}
}
}
$prevAttachments = !empty($attachments) ? $attachments.'|'.$prevAttachments : $prevAttachments;
try{
$stmt = $conn->prepare("EXEC [name].[dbo].[table] :p1,:p2");
$stmt->bindParam(':p1', $upl[$key], PDO::PARAM_INT);
$stmt->bindParam(':p2', $prevAttachments, PDO::PARAM_STR);
$stmt->execute();
}catch(PDOException $e){ echo 'ERROR: ' . $e->getMessage();}
}
}
In your code you never set or reset $files so that's why the value contains all previous files.
You should set $files = array(); at the beginning of each "row" to ensure $files only contains values for the specific row.

Database doesn't get input

I coded a function in PHP, which posts information of upload into a database table. If someone uploads a file, I will get the DateTime of the upload and his account number but I have an issue with the file name because the user is allowed to upload more than 1 file.
fdatum is Datetime
fmandantnr is User Number
fdateiname is Name of the file
The code is like following:
datensenden_copy.php
<?php
session_start();
require("../../require.php");
$omy= new clsMYSQL();
$output = '';
$fmandantnr=$_POST['fMandnr'];
for($i=0;$i<count($_FILES['userfiles']['name']);$i++) {
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
}
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
echo $query;
$omy->Query($query);
?>
I did my research and found out I need to get this:
for($i=0;$i<count($_FILES['userfiles']['name']);$i++){
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
}
Into this:
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
because the code cant get fdateiname in the SQL statement
Thank u for ur time.
You are looping over the $FILES array and getting the filename, but your INSERT command is OUTSIDE the loop so you only do ONE INSERT, with data from the last occurance in the loop. So simply move the insert inside the loop
In your code $fdatum does not appear to be defined anywhere, I hope/assume that was just left out of the sample code you gave us, or maybe it is created in the require.php code
<?php
session_start();
require("../../require.php");
$omy= new clsMYSQL();
$output = '';
$fmandantnr=$_POST['fMandnr'];
for($i=0;$i<count($_FILES['userfiles']['name']);$i++) {
echo $_FILES['userfiles']['name'][$i];
$f1name= $_FILES['userfiles']['name'][$i];
$query = "INSERT INTO email_hochladen
(fmandantnr,fdatum,fdateiname)
VALUES (". $fmandantnr.",".$fdatum.",".$fdateiname.")";
$omy->Query($query);
}
?>
Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
As I dont know anything about your clsMYSQL(); I cannot recode this to correctly use prepared statement.

Append variable To string in php insert

I'm having an issue appending a file name variable to a string in a sql insert like so
$insert = $mysqlConn->query("INSERT into images (image_name, url) VALUES ('".$fileName."', 'images/".$fileName."'");
I can do it with just the $fileName and it works fine but my syntax is wrong. I'm simply trying to make sure that every file name inserted starts with 'images/'
So if I'm inserting 'red.jpg' it would be 'images/red.jpg'
You can store image value into one variable
$imgPath = 'images/'.$fileName;
Above variable you can pass into the query
try this,you are missing one bracket
$insert = ("INSERT into images (image_name, url) VALUES ('".$fileName."', 'images/".$fileName."')");

PHP - Check for distinct filename on file upload

I'm pretty new to PHP. I hate to have to ask questions, because I'm sure this is documented somewhere, but after looking for a while, I just cannot seem to put two and two together.
I have a program that will allow multiple images to be uploaded to an item within the database. Basically, for each item in the database, there might be multiple image uploads.
Example:
Item: Xbox 360
Images:
Xbox360.jpg
side.jpg
front.jpg
The image and item information is all stored in the database (MySQL), but the images are stored within the filesystem, and the database points to the URL of the image(s) in the filesystem.
The problem I'm having is that everything works as expected, except it allows duplicate image names to be written to the database. It doesn't allow duplicate images to be written to the filesystem, which I'm happy with. I want to make sure that the name of an image is only added once to the database. If the image name is a duplicate to another, it needs to not write to the database.
add_db.php:
$uniqueDir = uniqid();
$directory = "img/$uniqueDir/";
db_addItem($id_category, $name, $cost, $description, $qty, $directory); //Adds to the `items` table
foreach ($_FILES['i_file']['name'] as $filename) {
if ($filename != '' && $filename != 'No file chosen') {
//I think above is where I check for unique image names
$url = "img/$uniqueDir/$filename";
db_addImg($url, $filename); //Adds to the `img` table
$item_picsID = get_item_PicsID($filename, $url);
$itemID = get_itemID($directory);
db_insertImg($itemID, $item_picsID);
}
}
addFilesystem($directory); //Writes image(s) to filesystem
function db_addImg($url, $filename) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO img (`name`, `url`) VALUES(:filename, :url)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':filename' => $filename,
':url' => $url
));
}
function db_insertImg($itemID, $item_picsID) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO `item_pics` (`item_id`, `img_id`) VALUES(:itemID, :item_picsID)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':itemID' => $itemID,
':item_picsID' => $item_picsID
));
$db = null;
return;
}
Everything works, except it will write duplicate image names to the database. I want the image names to be distinct. I also don't want to rename the images (if possible).
You can define an UNIQUE index on the name column in img table, and then use slightly modified INSERT statement in your db_addImg function:
function db_addImg($url, $filename) {
//...
$query = "INSERT INGORE INTO img (`name`, `url`) VALUES(:filename, :url)";
//...
}
It will quietly cancel any insert where the is a UNIQUE key collision, which will end up in distinct filenames across your img table.
I would use a filename based on the primary key from the img table as you're guaranteed it's unique.
Otherwise, you'll need to guess a unique filename with some type of hashing and then check the file system. All of which can be expensive operations.
Looks like you are using PDO, so the static method lastInsertId will get the last insert id (primary key).
For example:
// after your insert to img
$filename = 'img' . $db->lastInsertId() . $extension;
This will require changing the img table slightly. But you're better off storing meta data (file type, size, etc) in this table as opposed to the file location (as that can change).
I think better to use hash value of your url as the primary key. Be cause string searching is much slower as int.

php update database with image url, but don't overwrite existing value? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP image replacement?
I'm writing an edit script that allows a row to be updated in the database.
It starts by importing that row, then I wrap input boxes around the text areas which can be edited and updated.
That works great.
There are two url's stored in the database, http://www.mysite.com/images/image1.jpg and http://www.mysite.com/images/image2.jpg
What's the best way of checking if there are no new uploaded images on the edit form, to NOT update this field in the database?
I've tried using:
if ($image1new !="") { $image1==$image1new; } else { $image1 = $_POST['image1'];}
if ($image2new !="") { $image2==$image2new; } else { $image2 = $_POST['image2'];}
But that always passes a blank string?
Use $image1 = $image1new; instead of $image1 == $image1new;. You should use just a single = when you want to assign a value to a variable
If I understand, you want check if the input file have a file uploaded, and store that in DB, right?
First you need to retrieve, and store the ID of row in a variable, will assume that u will store that value in a variable called $id...
So I think u can try that:
if (isset($_FILES["input_file_name"]) {
$file = $_FILES["input_file_name"];
mysql_connect("server","user","pass") or die("Cannot access DB");
$sql_cmd = "UPDADE `database`.`table` SET `column` = '".$file."' WHERE `id` = ".$id.";";
mysql_query($sql_cmd);
}
else {
echo 'No images to store.';
}
Hope this can help.

Categories