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.

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

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图