简体   繁体   English

PDO插入查询无法使用PHP

[英]PDO insert query not working PHP

I'm using the following code to insert a bunch of records into a sqlite database: 我正在使用以下代码将一堆记录插入到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;
}

This is the $valuesPlaceholders: 这是$ valuesPlaceholders:

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

This is my $valuesArr : 这是我的$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
        )

)

This gives me the following errors: 这给了我以下错误:

Array to string conversion 数组到字符串的转换

PDOStatement::execute(): SQLSTATE[HY000]: General error: 25 column index out of range PDOStatement :: execute():SQLSTATE [HY000]:常规错误:25列索引超出范围

The table structure consists of 10 columns, including 1 id column, which is auto increment. 该表结构由10列组成,其中包括1个id列,它们是自动递增的。

What am I doing wrong ? 我究竟做错了什么 ?

****your function requires single dimensional array with strings or numbers in them, because you have multidimensional array, it tries to convert your inner arrays to strings so you get the error array to string conversion**** ****您的函数需要一维数组,其中包含字符串或数字,因为您具有多维数组,因此它会尝试将内部数组转换为字符串,从而将错误数组转换为字符串****

   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);

You've linked to another question in your comment , but you seem to have missed why the accepted answer works and your code doesn't. 您已在评论中 链接到另一个问题 ,但您似乎错过了为什么可接受的答案有效而您的代码无效的原因。

Specifically, the answer shows the creation of a new 1D array that is passed to the execute method: 具体来说,答案显示了如何创建新的一维数组,并将其传递给execute方法:

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

You haven't done this in your code and that's why it fails. 您尚未在代码中完成此操作,这就是失败的原因。

Unless you have a demonstrable need to use the above multi-insert technique I would recommend sticking to the standard methods: 除非您明显需要使用上述多插入技术,否则我建议您遵循标准方法:

$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();

You should also change $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); 您还应该更改$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); to $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); or your try/catch block is useless as PDO won't throw exceptions. 否则您的try/catch块将无用,因为PDO不会引发异常。

Try this syntax, It will work 100%. 试试这个语法,它将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;
    ?>

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

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