使用PHP函数进行PHP多次上传

时间:2018-01-10 12:25:51

标签: php pdo foreach

我尝试了解如何在PDO中使用多个上传。

所以我有我的post.php:

$database = new Database();
$db = $database->getConnection(); 
$media = new Media($db);

if($_POST){

 $image = !empty($_FILES["image"]["name"]) ? sha1_file($_FILES['image']['tmp_name']) . "-" .  time() .  "-" . basename($_FILES["image"]["name"]) : ""; 
 $media->image = $image;    

   if ($media->create()) {
     echo $media->uploadPhoto();
     $_POST=array();
   }
}

 <input name="image[]" type="file" />

我的media.php带有pdo查询和一些上传验证:

  public $image; 
  public $created;  

    public function create(){

    //write query
    $query = "INSERT INTO " . $this->table_name . "
    SET image=:image, 
    created=:created";

    $stmt = $this->conn->prepare($query);

    $this->image=htmlspecialchars(strip_tags($this->image));
    $stmt->bindParam(":image", $this->image);

    if($stmt->execute()){
        return true;
    }

    print_r($stmt->errorInfo());
    return false;
 }
 function uploadPhoto(){

    $result_message="";

    if(!empty($_FILES["image"]["tmp_name"])){
        $target_directory = "../uploads/";
        $target_file = $target_directory . $this->image;
        $file_type = pathinfo($target_file, PATHINFO_EXTENSION);
        $file_upload_error_messages="";
        $check = getimagesize($_FILES["image"]["tmp_name"]);
        if($check!==false){
        }else{
        $file_upload_error_messages.="<div></div>";
        }
        $allowed_file_types=array("jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "gif", "GIF");
        if(!in_array($file_type, $allowed_file_types)){
           $file_upload_error_messages.="<div></div>";
        }
        if(file_exists($target_file)){
        }
        if($_FILES['image']['size'] > (10485760)){
        $file_upload_error_messages.="<div></div>";
        }
        if(!is_dir($target_directory)){
           mkdir($target_directory, 0777, true);
        }
        if(empty($file_upload_error_messages)){
            if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){
            }else{
                $result_message.="<div></div>";
            }
        }
        else{
           $result_message.="{$file_upload_error_messages}";
        }
    }
    return $result_message;
}

所以我需要将值存储在不同的mysql记录中并将它们全部上传到服务器。

这样做的最佳方式是什么?将foreach放在哪里? 我正在与foreach的正确位置斗争......

$x=0;  
foreach ( $_FILES['image']['name'] AS $key => $value ){  
    // ...
    $x++;  
}

1 个答案:

答案 0 :(得分:0)

所以,如果这是你的foreach循环,并且你想为每个上传的文件插入不同的记录,那么使用mysqli_multi_query

  $x=0;  
  $query = "";
  foreach ( $_FILES['image']['name'] AS $key => $value ){  
     $query .= 'insert into tableName (col1,col2,col3,image)VALUES("a","b","c","'.$value.'");';
     $x++;  
  }
  $query = rtrim($query,";");
  mysqli_multi_query($connectionObj,$query);

你的查询看起来像这样

insert into tableName (col1,col2,col3,image)VALUES("a","b","c","a.jpg");
insert into tableName (col1,col2,col3,image)VALUES("a","b","c","b.jpg");