Jump to content
Sign in to follow this  
JesseElser15

PHP Upload Multiple Images With Captions Stored in MySQL - Jquery Add Input For Each New Image

Recommended Posts

I've written a script to store images in my database. The images have a caption that is also uploaded and stored. This was fairly easy to get working. I have a jquery function setup to add a new file input and caption input every time I click a button. This also works.

 

What is not working is my PHP is not uploading multiple files for some reason.

 

Could someone tell me what I have done wrong?

 

Thanks :)

 

HTML:

 

   


<form id="uploadMultiple" method="post" action="/scripts/php/imageUploadTest" enctype="multipart/form-data">
      <table class="fileUploadTable" id="uploadArea" cellspacing="0">
       <tr>
        <td>
         <label for="imageFile">Image:</label> 
         <input type="file" name="imageFile" accept=".jpg,.jpeg,.png,.gif">
        </td>
        <td>
         <label for="imageCaption">Image Caption:</label>
         <input type="text" name="imageCaption">
        </td>
        <td width="150px">
          
        </td>
       </tr>
       <tr id="uploadSubmission">
        <td>
         <input type="submit" value="Upload More" id="uploadMore">
        </td>
        <td>
         <input type="submit" value="Submit" name="addImage">
        </td>
        <td width="150px">
          
        </td>
       </tr>
      </table>
     </form>

JQuery for adding new elements:

 

    


$(function() {
            var scntDiv = $('#uploadArea');
            var i = $('#p_scents tr td').size() + 1;
            
            $('#uploadMore').live('click', function() {
                    $('<tr><td><label for="imageFile">Image:</label> <input type="file" name="imageFile" accept=".jpg,.jpeg,.png,.gif"></td><td><label for="imageCaption">Image Caption:</label> <input type="text" name="imageCaption"></td><td><a href="#" class="removeUpload" width="150px" style="text-align: center">Remove</a></td></tr>').insertBefore( $('#uploadSubmission') );
                    i++;
                    return false;
            });
            
            $('.removeUpload').live('click', function() { 
                    if( i > 1 ) {
                            $(this).parents('tr').remove();
                            i--;
                    }
                    return false;
            });
    });

 

And finally the PHP:

 

   


require($_SERVER['DOCUMENT_ROOT'].'/settings/globalVariables.php');
    require($_SERVER['DOCUMENT_ROOT'].'/settings/mysqli_connect.php');
    
    
    $db_name = 'imageUploads';
    $tbl_name = 'gallery';
    if(!$conn)
    {
      die('Could not connect: ' . mysqli_error());
    }
    mysqli_select_db($conn, "$db_name")or die("cannot select DB");
    
    foreach($_FILES['imageFile'] as $file){ 
    $caption = $_POST['imageCaption'];
    $uploadDir = 'http://www.example.com/images/'.'gallery/'; 
    $fileName = $_FILES['imageFile']['name'];
    $filePath = $uploadDir . $fileName;
    
    if(move_uploaded_file($_FILES["imageFile"]["tmp_name"],$_SERVER['DOCUMENT_ROOT']."/images/gallery/".$_FILES["imageFile"]["name"]))
    {
    $query_image = "INSERT INTO $tbl_name(filename,path,caption) VALUES ('$fileName','$uploadDir','$caption')";
    if(mysqli_query($conn, $query_image))
    {
    echo "Stored in: " . "gallery/" . $_FILES["imageFile"]["name"];
    }
    else
    {
    echo 'File name not stored in database';
    }
    }
    }

 

I was hoping I had it working properly for multiple images with my `foreach` loop but it only uploads one image even if I have 4 selected.

 

EDIT:

 

I've tried modifying my code to this and it's not working either but looking at tutorials this seems to be more on the right track than my previous code:

 

    r


equire($_SERVER['DOCUMENT_ROOT'].'/settings/globalVariables.php');
    require($_SERVER['DOCUMENT_ROOT'].'/settings/mysqli_connect.php');
    
    
    $db_name = 'imageUploads';
    $tbl_name = 'gallery';
    if(!$conn)
    {
      die('Could not connect: ' . mysqli_error());
    }
    mysqli_select_db($conn, "$db_name")or die("cannot select DB");
    
    foreach($_FILES['imageFile'] as $key => $name){ 
    $caption = $_POST['imageCaption'];
    $uploadDir = 'http://www.example.com/images/'.'gallery/'; 
    $fileName = $key.$_FILES['imageFile']['name'][$key];
    $file_size = $_FILES['files']['size'][$key];
    $file_tmp = $_FILES['files']['tmp_name'][$key];
    $file_type= $_FILES['files']['type'][$key];
    $filePath = $uploadDir . $fileName;
    
    if(move_uploaded_file($file_tmp,$_SERVER['DOCUMENT_ROOT']."/images/gallery/".$fileName))
    {
    $query_image = "INSERT INTO $tbl_name(filename,path,caption) VALUES ('$fileName','$uploadDir','$caption')";
    if(mysqli_query($conn, $query_image))
    {
    echo "Stored in: " . "gallery/" . $_FILES["imageFile"]["name"];
    }
    else
    {
    echo 'File name not stored in database';
    }
    }
    }

 

I've also added `[]` in the names of the HTML input elements that needed them.

Edited by JesseElser15

Share this post


Link to post
Share on other sites

To upload multiple files at once, the file input does need to be named with a [], like "imageFile[]". When you do that, $_FILES["imageFile"]["name", "size", etc] will be arrays. The caption input will need []s too, then the entry in $_POST will also be an array. Supposedly all the arrays will be of the same length, but you shouldn't assume that in your code.

 

Basically,

foreach ($_POST["imageCaption"] as $key => $caption) {
	$file = array(
		"name" => $_FILES["imageFile"]["name"][$key],
		"size" => $_FILES["imageFile"]["size"][$key],
		"tmp_name" => $_FILES["imageFile"]["tmp_name"][$key],
		"type" => $_FILES["imageFile"]["type"][$key]
	);

	// now you have $caption and $file to work with
}
Edited by requinix

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.