duanjiushu5063 2016-07-25 22:11
浏览 84
已采纳

foreach循环创建最后一次迭代的重复

So I have a php foreach loop which inserts however many images you upload in to a directory and creates a row in your DB for it. it works great except it is duplicating the last iteration.

I have tried doing an array_splice but that didn't work.

I know the query is subject to sql injections and will fix this once I get the iteration duplication sorted.

$errors= array();
foreach($_FILES['userfile']['tmp_name'] as $key => $tmp_name ){
    $file_name = time().$_FILES['userfile']['name'][$key];
    $file_size =$_FILES['userfile']['size'][$key];
    $file_tmp =$_FILES['userfile']['tmp_name'][$key];
    $file_type=$_FILES['userfile']['type'][$key];   
    if($file_size > 2097152){
        $errors[]='File size must be less than 2 MB';
    }       
    $query="INSERT INTO table (user_id, filename) VALUES ('$user_id', '$file_name')";
    $desired_dir="/items/";
    if(empty($errors)==true){
        if(is_dir($desired_dir)==false){
            mkdir("$desired_dir", 0700);        // Create directory if it does not exist
        }
        if(is_dir("$desired_dir/".$file_name)==false){
            move_uploaded_file($file_tmp,"/items/".$file_name);
        }else{                                  //rename the file if another one exist
            $new_dir="/items/".$file_name.time();
             rename($file_tmp,$new_dir) ;               
        }
        mysql_query($query);            
    }else{
            print_r($errors);
    }
}
if(empty($error)){
    echo "Success";
}
if ($conn->query($query) === TRUE) {
echo "done";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}

any ideas as to why its doing this?

thanks in advance!

  • 写回答

1条回答 默认 最新

  • douzhanbai9526 2016-07-25 23:29
    关注

    Inside the last if.. else.. section you're calling $conn->query($query). This will run whatever is in $query - in this case it will be the last value set inside your foreach loop. That's what's causing you to duplicate the last entry.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗