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

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.

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

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?