PHP,多个文件上传并获取mysql上传的每个文件的路径

时间:2014-01-19 20:41:11

标签: php mysql file-upload upload

我找到了这段代码,上传了多个文件

http://www.w3bees.com/2013/02/multiple-file-upload-with-php.html?showComment=1390161630156#c8075663254636569559

我修改了一些代码,用于获取每个上传集的唯一ID的upload /子目录文件夹;因此这些文件也获得了唯一的ID。

$dir=substr(uniqid(),-7); // Uniqid for subdirectory
$path = "uploads/$dir/"; // uploads/subdirectory/
mkdir($path, 0700); // Make directory
$valid_formats = array("jpg", "png", "jpeg", "kml");
$max_file_size = 2097152;
$count = 0;
    // Loop $_FILES to exeicute all files
    foreach ($_FILES['files']['name'] as $f => $name) {
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            }
            else{ // No error found! Move uploaded files 
                $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
                $uniq_name = substr(uniqid(),-5) . '.' .$ext;
                $dest = $path . $uniq_name;
                move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest);
                mysqli_query($dbc, "INSERT INTO files (code, name, path, type) VALUES ('$dir','$uniq_name','$dest','$ext')" );
                $count++; //Number of successfully uploaded file

            }
        }

    }

}

此过程正确执行。

我希望在move_upload_file之后,获取文件上传的所有路径(url)。 但是我只在数据库中插入第一个文件选择...其他路径文件正确上传,但没有插入数据库。

抱歉我的英语不好,这不是我的第一语言。我希望你能帮助我。

1 个答案:

答案 0 :(得分:0)

尝试

$sql_error = ''; // add this before you start the loop


if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)){
  $qry = "INSERT INTO files (code, name, path, type) VALUES ('$dir','$uniq_name','$dest','$ext')" ;

  $result = mysqli_query($dbc, $qry);
  if ( false===$result ) {
    $sql_error .= 'Error in the query '.$qry.'  Error Desc :'.mysqli_error($dbc).'<br /><br />' ;
  }
}

最后添加

echo $sql_error ;

在文件的末尾,如果有任何错误,它会在查询中显示错误。

还可以在

中添加查询
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)){}

表示只在文件上传时才添加。