Insert multiple file upload paths to database

Hey,

I have managed to get some code working using the PHP Manual. It uploads multiple images to my server, however i am having problems inserting each file path to my database…?

This is my code:-


                include("conn.php");



                $insert = "INSERT INTO category_selection (cat_id, selection_name, item_name, item_description, item_price, main_image, image_1, image_2, image_3, image_4, date_uploaded) VALUES

                (

                '".$_POST['thing']."',

                '".$_POST['txt_c_name']."',

                '".$_POST['txt_name']."',

                '".$_POST['txt_desc']."',

                '".$_POST['txt_price']."',

                '".$_FILES['ufile']."',

                '".$_FILES['ufile']."',

                '".$_FILES['ufile']."',

                '".$_FILES['ufile']."',

                '".$_FILES['ufile']."',

                now()

                )";

                $add_member = mysql_query($insert);



                //places files into same dir as form resides

                foreach ($_FILES["ufile"]["error"] as $key => $error)

                {

                   if ($error == UPLOAD_ERR_OK)

                   {

                       echo"$error_codes[$error]";

                       move_uploaded_file(

                         $_FILES["ufile"]["tmp_name"][$key],

                         'garments/'.$_FILES["ufile"]["name"][$key]

                       ) or die("Problems with upload");

                   }

                }

but the insert statement is not working, i think this is because i have 5 upload files, so i need to differentiate between them all. My form looks as so:-


        <form action="" name="update_mens" method="post" enctype="multipart/form-data">

        <table cellspacing="6">

        <tr><td>Main Image URL</td><td><input name="ufile[]" type="file" id="ufile[]"/></td></tr>

        <tr><td>Thumbnail 1</td><td><input name="ufile[]" type="file" id="ufile[]"/></td></tr>

        <tr><td>Thumbnail 2</td><td><input name="ufile[]" type="file" id="ufile[]"/></td></tr>

        <tr><td>Thumbnail 3</td><td><input name="ufile[]" type="file" id="ufile[]"/></td></tr>

        <tr><td>Thumbnail 4</td><td><input name="ufile[]" type="file" id="ufile[]"/></td></tr>

        <tr><td><input type="submit" name="btn_update" value="Upload"/></td></tr>

        </table>

        </form>

Can anyone help me acheive my goal?

Regards

Looks totally wrong to me. You need to use move_uploaded_file() on each file, and only after the file has been moved to a permanent location you can insert that location into the database.

Hey,

Thanks for replying, i have changed the code slightly to put the move before the insert as this would make more sense…


				//places files into same dir as form resides
				foreach ($_FILES["ufile"]["error"] as $key => $error)
				{
				   if ($error == UPLOAD_ERR_OK)
				   {
				       echo"$error_codes[$error]";
				       move_uploaded_file(
				         $_FILES["ufile"]["tmp_name"][$key],
				         'garments/'.$_FILES["ufile"]["name"][$key]
				       ) or die("<p style='color:red;padding:4px'>Problems with upload</p>");
				   }
				}
	
				include("conn.php");
																			
				$insert = "INSERT INTO category_selection (cat_id, selection_name, item_name, item_description, item_price, colours, main_image, image_1, image_2, image_3, image_4, date_uploaded) VALUES
				(
				'".$_POST['thing']."',
				'".$_POST['txt_c_name']."',
				'".$_POST['txt_name']."',
				'".$_POST['txt_desc']."',
				'".$_POST['txt_price']."',
				'".$_POST['txt_colours']."',
				'".$_FILES['ufile']."',
				'".$_FILES['ufile']."',
				'".$_FILES['ufile']."',
				'".$_FILES['ufile']."',
				'".$_FILES['ufile']."',
				now()
				)";
				$add_member = mysql_query($insert);
				}

The images all upload to the server fine, its the insert that does not work… can you point me in the right direction?

Regards

wrong again. You need to insert the value of the new file location, not the $_FILES[‘ufile’]

By the way, why you are inserting $_FILES[‘ufile’] as a value for all files, I just don’t know. At the very least it will not work simply because the $_FILES[‘ufile’] is actually an array and not a string.

Ok, is there an example of how i can do this tutorials etc…

I’ve come to a halt as i dont know how to write the code for inserting the uploaded file path… if there is 5 upload files how can find/write the upload path for all of them?

I personally will never use this way of uploading multiple files
<input name=“ufile” type=“file” id=“ufile”/>
(by the way, you cannot have the id=“ufile”> because it’s just invalid html.

Anyway, instead I would (and always do) use different names for each file like
<input name=“file1” type=“file” id=“f1”/>
<input name=“file2” type=“file” id=“f2”/>, etc.

Then you use the $_FILES array differently, like this:
foreach($_FILES as $aFile)
and then each $aFile will be an array with the usual keys ‘name’, ‘error’, etc.

thats exactly what i thought in the first place, i wanted to name the files differerntly but then followed this tutorial:-

http://us3.php.net/manual/en/features.file-upload.multiple.php

Anyway, i want to do it the right way, so to my understanding just to test the first file, would it be something like this?


				foreach ($_FILES as $aFile)
				{
				   if ($aFile == UPLOAD_ERR_OK)
				   {
				       echo"$error_codes[$error]";
				       move_uploaded_file($_FILES["file1"]["tmp_name"][$key],
				       'garments/'.$_FILES["file1"]["name"][$key])
				       or die("<p style='color:red;padding:4px'>Problems with upload</p>");
				   }
				}

No, you cannot use if ($aFile == UPLOAD_ERR_OK)
because $aFile is an array (hint for you: If variable starts with an $a or $arr, then it’s an array, it’s just a naming convention so that other programmers have a clue about type)

the correct way would be
$aMyUploads = array();
foreach($_FILES as $aFile){
if(0 === $aFile[‘error’]){
// create $newLocation path here…
$newLocation = ‘whatever’;
if(false !== move_uploaded_file($aFile[‘tmp_name’], $newLocation){
$aMyUploads = $newLocation;
}
}
}

// now you can use $aMyUploads array
$aMyUploads[0] is the new location of your first file,
$aMyUploads[1] is your second file, etc.

Hey,

Thanks, this code uploads the first file on the server:-


				$aMyUploads = array();
				foreach($_FILES as $aFile)
				{
					if(0 === $aFile['error'])
					{
					// create $newLocation path here...
					$newLocation = 'garments/'.$_FILES["file1"]["name"];
						if(false !== move_uploaded_file($aFile['tmp_name'], $newLocation))
						{
						$aMyUploads[] = $newLocation;
						}
					}
				}

Now if i want to add file2, 3, 4 and 5 do i need to add a new if? Sorry just bear with me i am fairly weak at the multiple image uploads…

I dont think i would need to add another if statement, could i do this:-


					$newLocation1 = 'garments/'.$_FILES["file1"]["name"];
					$newLocation2 = 'garments/'.$_FILES["file2"]["name"];
					$newLocation3 = 'garments/'.$_FILES["file3"]["name"];
					$newLocation4 = 'garments/'.$_FILES["file4"]["name"];


I know im just using trial and error, but i think its the best way il understand how it works…

Right, you don’t need another if statement but you also don’t need any of these:
$newLocation1 = ‘garments/’.$_FILES[“file1”][“name”];

                $newLocation2 = 'garments/'.$_FILES["file2"]["name"];

                $newLocation3 = 'garments/'.$_FILES["file3"]["name"];

                $newLocation4 = 'garments/'.$_FILES["file4"]["name"]; 

Just once, inside the loop:
$newLocation = ‘garments/’.$aFile[“name”];

Hey,

Thanks all the files upload perfectly now, only one issue i assumed that the following insert statement would work, but ‘$aMyUploads’ is not recognized… i tried using a constant to test if the insert works without $aMyUploads and it works… so this means $aMyUploads is the problem, have i missed something out?


				include("conn.php");
																			
				$insert = "INSERT INTO category_selection (cat_id, selection_name, item_name, item_description, item_price, colours, main_image, image_1, image_2, image_3, image_4, date_added) VALUES
				(
                '".$_POST['thing']."',
                '".$_POST['txt_c_name']."',
                '".$_POST['txt_name']."',
                '".$_POST['txt_desc']."',
                '".$_POST['txt_price']."',
                '".$_POST['txt_colours']."',
                $aMyUploads[0],
                $aMyUploads[1],
                $aMyUploads[2],
                $aMyUploads[3],
                $aMyUploads[4],
				now()
				)";
				$add_member = mysql_query($insert);

Regards

Hey,

Any ideas then on the code, i think i may have missed something out?

Regards

Hey billy, do you get an error message when you try and insert the values?

Do a bit of debugging:


echo $insert;

$add_member = mysql_query($insert) or die(mysql_error()); 

see if you get anything from those lines

Hard to tell. The best thing to do is to take a pick at what is in this array. Just add
print_r($aMyUploads);

somewhere before the insert statement and see what is printed.

Keep in mind that this array $aMyUploads will have values added to it only if the file was actually uploaded, so if you have a form with 5 upload fields but you only uploaded 2 files, then $aMyUploads will have only 2 elements.

So if you don’t expect users to always upload all 5 files, then you need to change the script like this:

find these lines:
if(0 === $aFile[‘error’])
{

// create $newLocation path here...

$newLocation = 'garments/'.$_FILES["file1"]["name"];

if(false !== move_uploaded_file($aFile['tmp_name'], $newLocation))

{

    $aMyUploads[] = $newLocation;

}

}

replace with these:

$newLocation = ‘garments/’.$aFile[“name”];
if(0 === $aFile[‘error’] && (false !== move_uploaded_file($aFile[‘tmp_name’], $newLocation))){
$aMyUploads = $newLocation;
} else {
$aMyUploads = ‘’;
}

Hey,

Thanks, i now have the following code:-


		<?php
		if (isset($_POST['btn_update']))
		{
			if($_POST['txt_c_name'] == "" || $_POST['txt_name'] == "" || $_POST['txt_desc'] == "" || $_POST['txt_price'] == "" || $_POST['txt_colours'] == "")
			{
			echo "<p style='color:red;padding:4px'>Please fill in all the fields.</p>";
			}
			elseif($_POST['thing'] == "0")
			{
			echo "<p style='color:red;padding:4px'>Please select a category.</p>";
			}
			else
			{	
				$aMyUploads = array();
				foreach($_FILES as $aFile)
				{
					$newLocation = 'garments/'.$aFile["name"];
					if(0 === $aFile['error'] && (false !== move_uploaded_file($aFile['tmp_name'], $newLocation)))
					{
					$aMyUploads[] = $newLocation;
					}
					else
					{
					$aMyUploads[] = '';
					}
				}
				
				print_r($aMyUploads);
				
				include("conn.php");
																			
				$insert = "INSERT INTO category_selection (cat_id, selection_name, item_name, item_description, item_price, colours, main_image, image_1, image_2, image_3, image_4, date_added) VALUES
				(
                '".$_POST['thing']."',
                '".$_POST['txt_c_name']."',
                '".$_POST['txt_name']."',
                '".$_POST['txt_desc']."',
                '".$_POST['txt_price']."',
                '".$_POST['txt_colours']."',
                $aMyUploads[0],
                $aMyUploads[1],
                $aMyUploads[2],
                $aMyUploads[3],
                $aMyUploads[4],
				now()
				)";
				$add_member = mysql_query($insert) or die(mysql_error());
			}
		}
		?>

When i do the insert i tried uploading inly one file out of the five to see what i get:-


Array ( [0] => garments/powered.png [1] => [2] => [3] => [4] => ) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , , now() )' at line 10

So it recognizes the first image which is fine but is saying i have a syntax error?

Try to include the values of $aMyUploads[0], and others in quotes:
’ “.$aMyUploads[0].” ',
’ “.$aMyUploads[1].” ',

Perfect, thanks

I appreciate the help.

Regards