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.

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

报告相同问题?

悬赏问题

  • ¥40 matlab调用ansys联合
  • ¥15 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下!
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)