上传的图像在数据库中存储两次

时间:2018-02-17 06:14:58

标签: php database image file mysqli

我正在使用php在投资组合基础网站上工作,当我将一个或两个图像上传到数据库时,存储在数据库中但是有两次,EG,当我上传一个图像命名为image.png,存储两次,如id = 1 name = image.png,id = 2 name = image.png。

enter image description here

下面添加了代码感谢您的帮助..!



 <?php
if (isset($_POST['upload'])) {
    if (count($_FILES['images']['name']) > 0) {
        for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
            $date       = date('d-m-Y');
            $images     = $_FILES['images']['name'][$i];
            $images_tmp = $_FILES['images']['tmp_name'][$i];
            if (empty($images)) {
                $error = "PLEASE SELECT AT LEAST ONE PHOTO.";
            } else {
                $insert_query = "INSERT INTO `portfolio` (`image_id`, `date`, `images`, `user_id`) VALUES (NULL, '$date', '$images', '" . $_SESSION['user_id'] . "')";
            }
            if (mysqli_query($con, $insert_query)) {
                $msg = "IMAGE UPLOADED TO YOUR PORTFOLIO";
            } else {
                $error = "IMAGE UPLOADING FAILED, PLEASE CHECK";
            }
            if (mysqli_query($con, $insert_query)) {
                move_uploaded_file($images_tmp, "../uploads/$images");
            }
        }
    }
}

?> 
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

可能是因为$i从值0开始,在for循环中初始化$ i = 1

for($i = 1; $i < count($_FILES['images']['name']); $i++){

或制作count($_FILES['images']['name'])-1

答案 1 :(得分:0)

  1. 验证您的输入
  2. 使用PDO和准备好的陈述
  3. 你的for循环正在循环遍历$ _FILES [&#39; images&#39;] [&#39; name&#39;]数组的任何内容。
  4. 您可以使用以下几种常用调试技术之一检查文件上传的内容:

    echo "<pre>";
    var_dump($_FILES);
    var_export($_FILES);
    print_r($_FILES);
    

    你应该发现它类似于:

    Array
    (
        [name] => Array
            (
                [0] => facepalm.jpg
                [1] => 
            )
    
        [type] => Array
            (
                [0] => image/jpeg
                [1] => 
            )
    
        [tmp_name] => Array
            (
                [0] => /tmp/phpn3FmFr
                [1] => 
            )
    
        [error] => Array
            (
                [0] => 0
                [1] => 4
            )
    
        [size] => Array
            (
                [0] => 15476
                [1] => 0
            )
    )
    

    看看:http://php.net/manual/en/features.file-upload.php