Skip to content
Advertisement

Multiple images not inserted into mysql database

I am unable to insert multiple images into database. When I am inserting the images, only one image is inserted. not all inserted. I have shown here the form with php insert code.I have not found where the problem is. Plz help.

$(document).ready(function() {
  if (window.File && window.FileList && window.FileReader) {
    $("#files").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;
      for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
          var file = e.target;
          $("<span class="pip">" +
            "<img class="imageThumb" src="" + e.target.result + "" title="" + file.name + ""/>" +
            "<br/><span class="remove">Remove image</span>" +
            "</span>").insertAfter("#files");
          $(".remove").click(function(){
            $(this).parent(".pip").remove();
          });
        });
        fileReader.readAsDataURL(f);
      }
    });
  } else {
    alert("Your browser doesn't support to File API")
  }
});

input[type="file"] {display: block;}
.imageThumb {max-height: 75px; border: 2px solid; padding: 1px; cursor: pointer;}
.pip {display: inline-block; margin: 10px 10px 0 0;}
.remove { display: block;background: #444;border: 1px solid black;color: white;text-align: center;cursor: pointer;}
.remove:hover {background: white;color: black;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3>Upload your images</h3>
  <input type="file" id="files" name="files[]" multiple /><br>
  <input type="submit" name="submit" value="Submit">
</div>

This is php code:

<?php
   if(isset($_POST['submit'])) 
      {
      if(isset($_FILES['files']))
         {

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        foreach ($tmp_name_arrays as $index => $val) 
        {
            $n_array = $n_arrays[$index];
            $tmp_name_array = $tmp_name_arrays[$index];
            $type_array = $type_arrays[$index];
            $size_array = $size_arrays[$index];

            if(move_uploaded_file($tmp_name_array, "ad/data/img/".$n_array))
            {
                $sql = 'INSERT INTO `image` 
                        SET `img_name` = ?, `img_type` = ?, `img_size` = ?';

                // Prepare the SQL statement for execution.
                $statement = $connection->prepare($sql);
                $bound = $statement->bind_param('sss', $n_array, $type_array, $size_array);

                // Execute the prepared statement.
                $executed2 = $statement->execute();

                if(!$executed2){
                    echo "error". mysqli_error($connection);
                } else {
                    $_SESSION['s']="Images successfully saved";
                    header('location:posting_ad_image.php');
                }
            }
        }
    }
 }
?>

I am able to upload only the last image that is uploaded last. All images are not inserted into phpmyadmin database.

Advertisement

Answer

As already noted your loop was hitting the redirect on the first iteration and then sending you off before all the images could be saved and logged. The use of prepared statements can be done in such a way that you do the preparation and binding of variables just once but execute many times until the statement is closed.

<?php

    if( isset( $_POST['submit'],$_FILES['files'] ) ) {

        $uploaded=array();

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];


        /* prepare the sql statement before the loop */
        $sql = 'INSERT INTO `image` SET `img_name` = ?, `img_type` = ?, `img_size` = ?';
        $statement = $connection->prepare( $sql );
        if( $statement ){

            /* if the statement was prepared successfully, bind the variables that will be used later */
            $statement->bind_param('sss', $n_array, $type_array, $size_array );


            /* iterate through the images, store the image and log to db */
            foreach( $tmp_name_arrays as $index => $val ){

                $n_array = $n_arrays[ $index ];
                $tmp_name_array = $tmp_name_arrays[ $index ];
                $type_array = $type_arrays[ $index ];
                $size_array = $size_arrays[ $index ];

                if( is_uploaded_file( $tmp_name_array ) ){
                    $bytes = move_uploaded_file( $tmp_name_array, "ad/data/img/".$n_array );
                    if( $bytes ){
                        $status = $statement->execute();
                        $uploaded[]=$status && $bytes ? $n_array : false;
                    }
                }
            }
            /* close the statement and db connection */
            $statement->close();
            $connection->close();

            /* remove empty entries from array - if any */
            $uploaded=array_filter( $uploaded );

            if( !empty( $uploaded ) ){
                $_SESSION['s']=sprintf("%d Images successfully saved", count( $uploaded )-1 );
                header('Location: posting_ad_image.php');
            }
        }
    }
?>

Ok – The following was done as a full, end-to-end test and works ok ~ you will need to edit the $dir variable to suit

<?php



    $dbhost =   'localhost';
    $dbuser =   'root'; 
    $dbpwd  =   'xxx'; 
    $dbname =   'xxx';
    $connection =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );



    $dir='c:/temp/fileuploads/1/';




    if( isset( $_POST['submit'], $_FILES['files'] ) ) {

        $uploaded=array();

        $sql = 'insert into `image` set `img_name` = ?, `img_type` = ?, `img_size` = ?';
        $stmt = $connection->prepare( $sql );


        if( $stmt ){

            $stmt->bind_param( 'sss', $name, $type, $size );

            foreach( $_FILES['files']['name'] as $i => $name ) {
                if( !empty( $_FILES['files']['tmp_name'][$i] ) ) {

                    $name = $_FILES['files']['name'][$i];
                    $size = $_FILES['files']['size'][$i];
                    $type = $_FILES['files']['type'][$i];
                    $tmp  = $_FILES['files']['tmp_name'][$i];


                    if( is_uploaded_file( $tmp ) ){
                        $bytes = move_uploaded_file( $tmp, $dir.$name );
                        if( $bytes ){
                            $status = $stmt->execute();
                            $uploaded[]=$status && $bytes ? $name : false;
                        }
                    }
                }
            }
            if( !empty( $uploaded ) ){
                $_SESSION['s']=sprintf("%d Images successfully saved", count( $uploaded )-1 );
                header('Location: posting_ad_image.php');
            }
        }
    }
?>
<!doctype html>
<html>
    <head><title>Multiple file upload</title></head>
    <body>
        <form method='post' enctype='multipart/form-data'>
            <input type='file' name='files[]' multiple />
            <input type='submit' name='submit' value='Upload & save' />
        </form>
    </body>
</html>

Snippet from db after running and uploading a few images at once

mysql> describe image;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| img_name | longblob    | YES  |     | NULL    |       |
| img_type | varchar(50) | YES  |     | NULL    |       |
| img_size | int(11)     | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+


mysql> select * from image;
+-------------------------------------+------------+----------+
| img_name                            | img_type   | img_size |
+-------------------------------------+------------+----------+
| tumblr_ook8swcsSt1tp499co1_1280.jpg | image/jpeg |    81124 |
| tumblr_ook8ukfiTY1tp499co1_1280.jpg | image/jpeg |   201061 |
| tumblr_ook8veeLgq1tp499co1_1280.jpg | image/jpeg |    63477 |
| tumblr_oomaozErOP1tp499co1_1280.jpg | image/jpeg |   283062 |
| tumblr_oomapxb8NJ1tp499co1_1280.jpg | image/jpeg |   577475 |
| tumblr_oomaqzKzlw1tp499co1_1280.jpg | image/jpeg |   382917 |
+-------------------------------------+------------+----------+
Advertisement