简体   繁体   中英

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

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. Like

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

So for your case, you should execute inside a foreach

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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