4

I've setup a form to upload multiple files from a PHP script and then insert it into the Database with path. Here's my code

<form action="" method="post" enctype="multipart/form-data">
<tr class='first'>
    <td>Property Image : </td>
    <td>
        <input type="file" name="pic_upload[]" >
        <input type="file" name="pic_upload[]" >
        <input type="file" name="pic_upload[]" >
    </td>
</tr>
<tr class='first'>
    <td>&nbsp;</td><td><input type="submit" name="create" value="Add"  /></td>
</tr>
</form>
<?php
if(isset($_POST['create'])) {
    $path = "images/";
    for ($i=0; $i<count($_FILES['pic_upload']['name']); $i++) {
        $ext = explode('.', basename( $_FILES['pic_upload']['name'][$i]));
        $path = $path . md5(uniqid()) . "." . $ext[count($ext)-1]; 
        move_uploaded_file($_FILES['pic_upload']['tmp_name'][$i], $path);
    }
    $sql = "INSERT INTO post (`image`) VALUES ('$path');";
    $res = mysqli_query($con,$sql) or die("<p>Query Error".mysqli_error()."</p>");
    echo "<p>Post Created $date</p>";
}
?>  

The Script runs successfully, but at the database end inside the column it looks like this.

images/8de3581eb72ee7b39461df48ff16f4a3.jpg024fae942ae8c550a4bd1a9e028d4033.jpg380cc327df25bc490b83c779511c015b.jpg

Help me out with this please

4
  • general warning: you're simply assuming uploads will always succeed. BAD idea. never assume success. always assume failure, check for that failure, and treat success as a pleasant surprise. Commented Dec 18, 2014 at 21:56
  • Well, I've roamed around alot & i guess i couldn't understand it that's why came up here & asked. What i felt was SQL statement to be the barrier. It would be kind of you if you can help me out with this Commented Dec 18, 2014 at 22:02
  • your problem is that you just keep appending more text to $path without ever erasing the previous file's text. there's nothing wrong with your query - it's your $path = $path . etc... line. Commented Dec 18, 2014 at 22:03
  • Thanks Marc, I've Fixed it & yes it was the $path making fuss. Commented Dec 18, 2014 at 22:20

3 Answers 3

2

Move $path = "images/"; inside the for loop. Otherwise you are appending to the filename without resetting it after each iteration. Actually, you don't need to use a variable for that prefix at all. You can simply write 'images/' . md5(uniqid()) . "." . $ext[count($ext)-1] immediately.

To write the values to the database, you can either run the query in each iteration as well or add the paths to an array which is transformed to the comma-separated insertion list according to the SQL syntax.

Sign up to request clarification or add additional context in comments.

4 Comments

The thing is if i move it inside the loop it just inserts the last file path to the database. What i wanted is to make a new entry against each image been uploaded so i can get the path for every image separately.
You can either run the query inside the loop as well (prepared statements are recommended) or make an array.
for($i=0; $i<count($_FILES['pic_upload']['name']); $i++){ $ext = explode('.', basename( $_FILES['pic_upload']['name'][$i])); $path = "images/" . md5(uniqid()) . "." . $ext[count($ext)-1]; move_uploaded_file($_FILES['pic_upload']['tmp_name'][$i], $path); $sql = "INSERT INTO post (image) VALUES ('$path')"; } Same thing. Making a single entry to database while I've uploaded 3 images and no path to database column even
Don't concatenate the string. Save the filenames to an array and generate the sql syntax. The values must be comma-separated and written in parentheses for each row, such as INSERT INTO post (image) VALUES ('path1'), ('path2'), ('path3'), …
1

Here is what worked for me:everything contained in the for loop then just return the $fileDest

<?php
if(isset($_POST['submit'])){
  $total = count($_FILES['files']['tmp_name']);
  for($i=0;$i<$total;$i++){
    $fileName = $_FILES['files']['name'][$i];
    $ext = pathinfo($fileName, PATHINFO_EXTENSION);
    $newFileName = md5(uniqid());
    $fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
    if($ext === 'pdf' || 'jpeg' || 'JPG'){
        move_uploaded_file($_FILES['files']['tmp_name'][$i], $fileDest);
    }else{
      echo 'Pdfs and jpegs only please';
    }
  }
}

 ?>



 <!DOCTYPE html>
 <html lang="en" dir="ltr">
   <head>
     <meta charset="utf-8">
     <title></title>
   </head>
   <body>

     <form class="" action="test.php" method="post" enctype="multipart/form-data">
       <input type="file" name="files[]" multiple>
       <button type="submit" name="submit">Upload</button>
     </form>

   </body>
 </html>

Comments

0
$files = array_filter($_FILES['lamp']['name']); 

$total = count($files); 

$path = "./asset/save_location/";

// looping for save file to local folder
for( $i=0 ; $i < $total ; $i++ ) {
    $ext = explode('.', basename( $_FILES['lamp']['name'][$i]));
    $tmpFilePath = $_FILES['lamp']['tmp_name'][$i]; 

    if ($tmpFilePath != ""){

        $newFilePath = $path .date('md').$i.".".$ext[count($ext)-1];  //save lampiran ke folder $path dengan format no_surat_tgl_bulan_nourut

        // upload success 
        if(move_uploaded_file($tmpFilePath,$newFilePath)) {
            $success="file uploaded";
        }
    }

} //end for 

//looping for save namefile to database 
for ($i=0; $i<count($_FILES['lamp']['name']); $i++) {
    $ext = explode('.', basename( $_FILES['lamp']['name'][$i]));
    $path = $path .date('md') .$i. "." . $ext[count($ext)-1].";"; 
    $save_dir=substr($path, 22,-1);

}//end for
var_dump($save_dir);die();

1 Comment

Welcome to StackOverflow :-) It is great to see that you want to help others improve their programming. Yet, please do not simply post code as an answer. Explain why your code answers the question and highlight the most important parts of it in your explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.