多个文件上传并只存储一个MySQL数据库的文件路径

时间:2016-10-17 06:03:12

标签: php mysql file-upload

这是简单的html文件代码

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

这是简单的PHP文件代码

<?php
$IMG = isset($_POST['files']) ? $_POST['files'] : array();

if (!empty($IMG)) 
{
$uploads_dir = 'images/';
foreach ($IMG["error"] as $key => $error)
{
  if ($error == UPLOAD_ERR_OK)
{
      $tmp_name = $IMG["tmp_name"][$key];
      $name = $IMG["name"][$key];
      move_uploaded_file($tmp_name, "$uploads_dir/".$name);
      $name_array=mysql_real_escape_string($name);
      $value_insert[] = "('" . $name_array . "')";
   }
}
$values_insert = implode(',', $value_insert);
  $query = "INSERT INTO upload (FILE_NAME) VALUES" . $values_insert;
  $result = mysql_query($query);
  }else{
 echo 'empty array';
  }

 ?>

当我使用此代码时,它会给我'空数组'错误但文件无法上传。

2 个答案:

答案 0 :(得分:0)

<?php
    $IMG = isset($_FILES['files']) ? $_FILES['files'] : array();

    if (!empty($IMG)) 
    {
        $uploads_dir = 'images/';
        $value_insert = '';
        foreach ($IMG["error"] as $key => $error)
        {
            if ($error == UPLOAD_ERR_OK)
            {
              $tmp_name = $IMG["tmp_name"][$key];
              $name = $IMG["name"][$key];
              move_uploaded_file($tmp_name, "$uploads_dir/".$name);
              $name_array=mysql_real_escape_string($name);
              $value_insert .= $name_array . ",";
            }
        }
         $values_insert = rtrim($value_insert, ',');
          $query = "INSERT INTO upload (FILE_NAME) VALUES" . $values_insert;
          $result = mysql_query($query);
     }else{
        echo 'empty array';
     }

?>

答案 1 :(得分:0)

这是演示代码

<?php
$IMG = isset($_FILES['files']) ? $_FILES['files'] : array();

if (!empty($IMG)) 
{
    $uploads_dir = 'images/';
    $i = 1;
    foreach ($IMG["error"] as $key => $error)
    {
        if ($error == UPLOAD_ERR_OK)
        {
          $tmp_name = $IMG["tmp_name"][$key];
          $name = $IMG["name"][$key];
          move_uploaded_file($tmp_name, "$uploads_dir/".$name);
          $name_array=mysql_real_escape_string($name);
          if ($i == 1) {
             $query = "INSERT INTO upload (FILE_NAME) VALUES" . $name_array;
             $result = mysql_query($query);
             if (!$result) {
                 die('Invalid query: ' . mysql_error());
             }
          }
          $i++;
        }
    }         

 }else{
    echo 'empty array';
 }

?>