简体   繁体   English

如何使用 PHP 将数据数组插入数据库?

[英]How to insert an array of data into the database using PHP?

I am getting the array value like below我得到如下的数组值

Array
(
    [0] => Array
        (
            [upload_label] => label 1
            [upload_name] => 100-best_1940225136.png
            [society_id] => 57
        )

    [1] => Array
        (
            [upload_label] => label 2
            [upload_name] => 150x150_2147441709.png
            [s_id] => 57
        )

)

Now I have to insert the data into the database.现在我必须将数据插入数据库。 So I used below inert code所以我使用了下面的惰性代码

$sqlUpload="INSERT INTO `tbl_uploadAll`(upload_label,upload_name,s_id) VALUES (:upload_label,:upload_name,:s_id)";
$stmt= $pdo->prepare($sqlUpload);
$stmt->execute($dataupload);

when I hit the button then am getting 500 error in the network tab当我按下按钮时,在网络选项卡中出现 500 错误

My full code here我的完整代码在这里

if (isset($_POST['send'])) {


$total = count($_FILES['docUpload']['name']);
$dataupload=array();
for($i=0; $i < $total; $i++) {

if(isset($_FILES['docUpload']['name'][$i]) && $_FILES['docUpload']['name'][$i] != "")
{
    $foldername="profile";
    $uploadLabel=$_POST['docUploadLabel'][$i];

      $image1  = $_FILES['docUpload']['name'][$i];
      $filename  = basename($image1);
      $onlyfile = pathinfo($filename, PATHINFO_FILENAME);
      $extension = pathinfo($filename, PATHINFO_EXTENSION);

      $file      = mt_rand();// random number 
      $newname   = $onlyfile.'_'.$file.'.'.$extension;
       
      //$location='images/'.$foldername.'/'.$newname;
       $location='../assets/images/uploads/'.$foldername.'/'.$newname;


      if($extension=='png' || $extension=='jpg' || $extension=='jpeg') { 
        compressImage($_FILES['docUpload']['tmp_name'][$i],$location,60); 
      } 
      else{ 
        move_uploaded_file($_FILES['docUpload']['tmp_name'][$i], $location); 
      }
    $uploadDoc=$newname;


    $dataupload[]=array(
         'upload_label'=>$uploadLabel,
         'upload_name'=>$uploadDoc,
         's_id'=>$last_id,
      );

 }


}

echo"<pre>";
print_r($dataupload);
$sqlUpload="INSERT INTO `tbl_uploadAll`(upload_label,upload_name,s_id) VALUES (:upload_label,:upload_name,:s_id)";
$stmt= $pdo->prepare($sqlUpload);
$stmt->execute($dataupload);

}

You are passing array of array您正在传递数组数组

$stmt->execute($dataupload);

execute expects an array of key => value where key should be named placeholders. execute需要一个 key => value 的数组,其中 key 应该被命名为占位符。 Like喜欢

$data = [
    'name' => $name,
    'surname' => $surname,
    'sex' => $sex,
];

So for your case, you should execute inside a foreach因此,对于您的情况,您应该在 foreach 中执行

foreach ($dataupload as $row)
    {
        $stmt->execute($row);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM