PDO Prepared Inserts multiple rows in single query

后端 未结 22 2079
感情败类
感情败类 2020-11-21 23:38

I am currently using this type of SQL on MySQL to insert multiple rows of values in one single query:

INSERT INTO `tbl` (`key1`,`key2`) VALUES (\'r1v1\',\'r1         


        
22条回答
  •  攒了一身酷
    2020-11-21 23:47

    test.php

     'balasubramani',
        'status' => 1
        ),
        array(
        'name' => 'balakumar',
        'status' => 1
        ),
        array(
        'name' => 'mani',
        'status' => 1
        )
    );
    
    var_dump($obj->insertMultiple($table,$rows));
    ?>
    

    Database.php

    dbh = new PDO('mysql:host='.$this->host.';dbname='.$this->database.'', $this->user, $this->pass);
                //print "Connected Successfully";
            } 
            catch (PDOException $e) {
                print "Error!: " . $e->getMessage() . "
    "; die(); } } /* Insert Multiple Rows in a table */ public function insertMultiple($table,$rows){ $this->dbh->beginTransaction(); // also helps speed up your inserts. $insert_values = array(); foreach($rows as $d){ $question_marks[] = '(' . $this->placeholders('?', sizeof($d)) . ')'; $insert_values = array_merge($insert_values, array_values($d)); $datafields = array_keys($d); } $sql = "INSERT INTO $table (" . implode(",", $datafields ) . ") VALUES " . implode(',', $question_marks); $stmt = $this->dbh->prepare ($sql); try { $stmt->execute($insert_values); } catch (PDOException $e){ echo $e->getMessage(); } return $this->dbh->commit(); } /* placeholders for prepared statements like (?,?,?) */ function placeholders($text, $count=0, $separator=","){ $result = array(); if($count > 0){ for($x=0; $x<$count; $x++){ $result[] = $text; } } return implode($separator, $result); } } ?>

提交回复
热议问题