简体   繁体   中英

PHP Inserting array values into MySQL prepared statement

I have an array of values that I am trying to insert into a database. Currently the below only inserts the first key value pair in the array and then returns an error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General       error' in /_/components/php/functions.php:33
Stack trace:
0 /_/components/php/functions.php(33): PDOStatement->fetchAll()
1 /testdb.php(44): Photo\DB\query('INSERT into cat...', Array, Object(PDO))
2 {main} thrown in /_/components/php/functions.php on line 33

line 33 in functions.php is in this function

function query($query, $bindings, $conn){
    $stmt = $conn->prepare($query);
    $stmt->execute($bindings);
    $results = $stmt->fetchAll();  <---line 33

    return $results ? $results : false;
}

The main code is

foreach ($sitecategories as $key => $value) {
    // print "this is key $key and this is value $value";
    if ( $conn ) {
        $catquery=query("INSERT into categories (cat_id, label) VALUES (:catid, :label)",
        array('catid'=>$key, 'label'=>$value), 
        $conn);
    } else {
        print "could not connect to the database";
    }
}

So I am connecting OK to the DB (elsewhere in the code) and the first key value pair is inserted successfully but not the rest of the array. I'm guessing my syntax is incorrect somewhere in

array('catid'=>$key, 'label'=>$value),

but I can't figure it out. Any help much appreciated!

You shouldn't fetchAll() after you INSERT . INSERT has no result set.

I just ran a test of inserting and then calling fetchAll() on the PDOStatement object, and I confirm that this causes the "General error" exception you showed.

$stmt = $dbh->prepare("insert into foo () values ()");
$stmt->execute();
$result = $stmt->fetchAll();

Throws:

PHP Fatal error:  Uncaught exception 'PDOException' with message 
'SQLSTATE[HY000]: General error' in /Users/billkarwin/workspace/PHP/21194489.php:14
Stack trace:
#0 /Users/billkarwin/workspace/PHP/21194489.php(14): PDOStatement->fetchAll()
#1 {main}
  thrown in /Users/billkarwin/workspace/PHP/21194489.php on line 14

Your array of values is incorrect. The keys need to have the : , too.

array(':catid'=>$key, ':label'=>$value)

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