PDO将多行插入MySQL表

时间:2019-03-25 21:22:33

标签: php mysql pdo

基于此示例,我试图在单个查询中插入多行:  [链接] [1]:http://thisinterestsme.com/pdo-prepared-multi-inserts/

但是没有插入值。

    $pdo = new PDO("mysql:host=$this->host;dbname=$this->database", $this->login, 
$this->password);
    $columnNames = array_keys($dataVals[0]);
    unset($columnNames["8"]);
    unset($columnNames["9"]);
    foreach ($dataVals as $arrayIndex => $row) {
        $params = array();
        foreach ($row as $columnName => $columnValue) {
            $param = ":".$columnName.$arrayIndex;
            $params[] = $param;
            $toBind[$param] = $columnValue;
        }
        $rowsSQL[] = "(".implode(", ", $params).")";
    }
    $sql = "INSERT INTO `$this->table` (".implode(", ", $columnNames).") VALUES ".implode(", ", $rowsSQL);
    $pdoStatement = $pdo->prepare($sql);
    foreach ($toBind as $param => $val) {
        $pdoStatement->bindParam($param, $val);
    }
    $pdoStatement->execute();

0 个答案:

没有答案