使用PDO上传动态文件数

时间:2017-07-13 06:44:05

标签: php pdo

编辑 Here is a similar thread

我正在尝试从动态HTML表单上传潜在的多个文件。

<button>能够将图像输入添加到表单中,如下所示:

<button onclick="addImage()">Add Image</button>  

附加<script>功能,可添加图片<input>

function addImage() {
    $("form").append('<div><input type="file" name="image[]" id="uploadImage" multiple><button class="remove">Remove</button></div>');
}

当我单击表单的“上载”按钮时,不会抛出任何错误,但文件不会在数据库或图像文件夹中结束。

以下是PHP PDO尝试完成这项工作:

//SQL Statement
$statementImage = $db->prepare("INSERT INTO table (date, title, image) value (:date, :title, :image)");

//if an image is prepared for upload
if(isset($_FILES['image']['name'])) {

    //if no image was attached to upload input
    foreach($_FILES['image']['error'] as $err){
        switch ($err){
            case UPLOAD_ERR_NO_FILE:
            echo 'No file sent.';
            exit;
            }
        }

    //check for correct extension
    for($x=0; $x<count($_FILES['image']['tmp_name']); $x++){

        $file_name = $_FILES['image']['name'][$x];
        $file_tmp = $_FILES['image']['tmp_name'][$x];

        $t = explode(".", $file_name);
        $t1 = end($t);
        $file_ext = strtolower(end($t));

        $ext_check = array("jpg", "jpeg", "png", "gif", "svg");

        //move file to folder
        if(in_array($file_ext, $ext_check)){
            $filer = $file_tmp;
            $filepath = "images/" . $file_name;
            move_uploaded_file($filer, $filepath);

            //SQL statement
            $statementImage->execute(['date' => $date, 'title' => $title, 'image' => $file_name]);
            } else{
                echo "Only images can be stored.";
            }
        }
    }
}

我有点想知道if(isset($_FILES['image']['name'])) {是否是询问文件是否已附加到输入的正确方法。

0 个答案:

没有答案