使用PHP将多个映像上载到MYSQL数据库中

时间:2014-11-05 16:10:13

标签: php html mysql image post

我目前非常困惑为什么我无法将数组图像插入到我的数据库中。 截至目前,我目前的多文件上传能够将图像上传到我的默认目录,并且只能将第一张图像存储到我的SQL服务器数据库中,为什么会这样呢? foreach命令不应该能够将我上传的所有多个文件分别分别存储到数据库中吗?请详细说明,谢谢!

HTML代码

<form method="post" enctype="multipart/form-data"  action="">  
    <input type="file" name="files[]" id="files" multiple />  
    <br /><br />
    <button type="submit">Upload selected files</button>  

PHP代码

foreach ($_FILES["files"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $name = $_FILES["files"]["name"][$key];
            move_uploaded_file($_FILES["files"]["tmp_name"][$key], "" . $_FILES['files']['name'][$key]);
            $sql = "INSERT INTO `test`(`image`) VALUES ('" . $name . "')";
            $result = mysqli_query($connection, $sql);
            echo "The file " . basename($_FILES['multiple_uploaded_files']['name']) . " has been uploaded";
        } else {
            echo "There was an error uploading the file, please try again!";
        }
    }

干杯, 正在学习的科技新手。

1 个答案:

答案 0 :(得分:1)

try with this example code,

    $path = "imageuploads/";
     for($i=0; $i<count($_FILES['file']['name']); $i++){
     $extension = explode('.', basename( $_FILES['file']['name'][$i]));
     $path = $path . md5(uniqid()) . "." . $extension[count($extension)-1]; 

      if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $path )) {
      //insert query 
         echo "uploaded successfully";
          } else{
        echo "Error in Upload";
       }
   }
Above code is not worked, please tell the scenario