php / mysql - 多个文件上传未正确插入表中

时间:2016-01-01 03:34:01

标签: php mysql

这是我上传的php文件的片段。

完成上传后,文件会上传到正确的文件夹中(即:move_uploaded_file)。

但是,它们在表格中没有正确显示(表中只有第一个文件正确)。

我做错了什么?

    $con = mysqli_connect($theDb, $usr, $pass, "images");
    mysqli_select_db($con, "images");

//Submit button work
if(isset($_POST['submit'])){
  for($i=0; $i<count($_FILES['file_img']['name']);$i++){
    $filetmp = $_FILES["file_img"]["tmp_name"][$i];
    $filename = $_FILES["file_img"]["name"][$i];
    $filetype = $_FILES["file_img"]["type"][$i];

    $selected = $_POST['tables'];

    //image type check
    if(substr($filetype, 6) == "jpeg"){

      $filepath = "categories/" . $selected . "/" . $filename; //insert in respective folders
      move_uploaded_file($filetmp,$filepath);

      $sql = "INSERT INTO `$selected` (img_name, img_path, img_type) VALUES ('$filename', '$filepath', '$filetype')";

    } 
    else{
      echo "Has to be an image!";
    }
  }
  $result = mysqli_query($con, $sql);
}

更新:

<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file_img[]" id="file" multiple/>
<input type="submit" name="submit" value="Upload" />

<?php
include '/var/db_file.php';

$con = mysqli_connect($theDb, $usr, $pass, "images");
mysqli_select_db($con, "images");

// Drop down menu
$dbname = "images";
$sql = "SHOW TABLES FROM $dbname";
$result = mysqli_query($con, $sql);
$tableNames = array();

while ($row = mysqli_fetch_row($result)) {
    $tableNames[] = $row[0];
}

echo '<br>';

echo '<select name="tables" id="tables">';
foreach ($tableNames as $name) {
    echo '<option value="' . $name . '">' . $name . '</option>';
}
echo '</select>';
// Drop down menu end

echo '<br>';

mysqli_close($con);
?>

代码的剩余部分继续执行第一个代码块。两个代码块都包含在表单标记

1 个答案:

答案 0 :(得分:3)

$result = mysqli_query($con, $sql);

这应该在for循环中

所以你的第一个区块代码应该是这样的:

$con = mysqli_connect($theDb, $usr, $pass, "images");
    mysqli_select_db($con, "images");

//Submit button work
if(isset($_POST['submit'])){
  for($i=0; $i<count($_FILES['file_img']['name']);$i++){
    $filetmp = $_FILES["file_img"]["tmp_name"][$i];
    $filename = $_FILES["file_img"]["name"][$i];
    $filetype = $_FILES["file_img"]["type"][$i];

    $selected = $_POST['tables'];

    //image type check
    if(substr($filetype, 6) == "jpeg"){

      $filepath = "categories/" . $selected . "/" . $filename; //insert in respective folders
      move_uploaded_file($filetmp,$filepath);

      $sql = "INSERT INTO `$selected` (img_name, img_path, img_type) VALUES ('$filename', '$filepath', '$filetype')";
      $result = mysqli_query($con, $sql);
    } 
    else{
      echo "Has to be an image!";
    }
  }

}

如果您有更多问题,请告诉我