PDO插入查询无法使用PHP

时间:2018-06-19 12:43:05

标签: php pdo sqlite

我正在使用以下代码将一堆记录插入sqlite数据库:

try {
    $dir = 'sqlite:file_name';
    $dbh  = new PDO($dir) or die("cannot open the database");
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

    $query_str = 'DELETE FROM mytable; INSERT INTO mytable (field1, field2, field3, field4, field5, field6, field7, field8, field9) VALUES ';
    $query = $dbh->prepare( $query_str . $valuesPlaceholders);
    $sqlResponse = $query->execute($valuesArr);
}
catch (PDOException $e) {
    if ($e->getCode() == 1062) {
        echo 'here';
    } else {
        throw $e;
}

这是$ values占位符:

(?, ?, ?, ?, ?, ?, ?, ?, ?),(?, ?, ?, ?, ?, ?, ?, ?, ?),(?, ?, ?, ?, ?, ?, ?, ?, ?)

这是我的$valuesArr

Array
(
    [0] => Array
        (
            [0] => temperature
            [1] => M1
            [2] => 40110
            [3] => 100
            [4] => 500
            [5] => 200
            [6] => 300
            [7] => 1
            [8] => C
        )

    [1] => Array
        (
            [0] => humidity
            [1] => M1
            [2] => 40114
            [3] => 100
            [4] => 500 
            [5] => 200
            [6] => 300
            [7] => 1
            [8] => %
        )

    [2] => Array
        (
            [0] => param111
            [1] => M2
            [2] => 40115
            [3] => 100.5
            [4] => 500
            [5] => 200
            [6] => 300
            [7] => 0.1
            [8] => uni
        )

)

这给了我以下错误:

  

数组到字符串的转换

     

PDOStatement :: execute():SQLSTATE [HY000]:常规错误:25列索引超出范围

表结构由10列组成,其中包括1 id列,它们是自动递增的。

我在做什么错了?

3 个答案:

答案 0 :(得分:0)

****您的函数需要一维数组,其中包含字符串或数字,       因为您有多维数组,所以它会尝试将内部数组转换为字符串,从而将错误数组转换为字符串****

   Convert the values to single array,

    $values_str =''; 
    $i = 0;
    foreach($valuesArr as $ar){
      if($i > 0)$values_str.=',';
      $values_str .= implode(',',$ar);
      $i++;
    }
    $values_str = explode(',', $values_str);
    //I dont know whether you would need this array_map or not
    array_map('strin_function', $values_str);
    function strin_function($val){
      return "'".$val."'";
    }
    $valuesArr = $values_str;
    var_dump($valuesArr);

答案 1 :(得分:0)

您在linked to another question中输入了comment,但是您似乎错过了为什么可接受的答案有效而您的代码无效的原因。

具体来说,答案显示了如何创建新的一维数组,该数组将传递给execute方法:

...
foreach($data as $d){
    $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
    $insert_values = array_merge($insert_values, array_values($d));
}
...

您尚未在代码中完成此操作,这就是失败的原因。

除非您明显需要使用上述多插入技术,否则我建议您遵循标准方法:

$dbh->beginTransaction();
$dbh->exec('DELETE FROM mytable');
$query = $dbh->prepare(
    'INSERT INTO mytable (field1, field2, field3, field4, field5, field6, field7, field8, field9) VALUES (?,?,?,?,?,?,?,?,?)'
);
foreach ($valuesArr as $arr) {
    $query->execute($arr);
}
$dbh->commit();

您还应该将$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );更改为$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );或您的try/catch块无用,因为PDO不会引发异常。

答案 2 :(得分:-2)

尝试以下语法, 它将100%起作用。

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDBPDO";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "INSERT INTO MyGuests (firstname, lastname, email)
        VALUES ('John', 'Doe', 'john@example.com')";
        // use exec() because no results are returned
        $conn->exec($sql);
        echo "New record created successfully";
        }
    catch(PDOException $e)
        {
        echo $sql . "<br>" . $e->getMessage();
        }

    $conn = null;
    ?>