多个图像未插入mysql数据库

时间:2017-12-09 08:37:51

标签: javascript php html mysql file-upload

我无法将多个图像插入数据库。插入图像时,只插入一个图像。并非全部插入。我在这里显示了php插入代码的形式。我还没有找到问题所在。 Plz帮助。

$(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>

这是php代码:

<?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');
                }
            }
        }
    }
 }
?>

我只能上传最后上传的最后一张图片。所有图像都未插入phpmyadmin数据库。

2 个答案:

答案 0 :(得分:1)

问题是您在上传第一张图片后重定向到页面。你需要改变你的if-else统计数据。

<?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');// add it here after for loop
    }

 }
?>

答案 1 :(得分:1)

如前所述,您的循环在第一次迭代时遇到redirect,然后在保存并记录所有图像之前将其发送出去。 prepared statements的使用可以通过以下方式完成:您只需执行一次变量的准备和绑定,但执行多次直到语句关闭。

<?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');
            }
        }
    }
?>

好的 - 以下是作为完整的端到端测试完成并且正常工作〜您需要编辑$dir变量以适合

<?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>
运行并一次上传几张图片后,

来自db的片段

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 |
+-------------------------------------+------------+----------+