1

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!

Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115
Stuart Brown
  • 977
  • 2
  • 22
  • 47

2 Answers2

3

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
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
0

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

array(':catid'=>$key, ':label'=>$value)
gen_Eric
  • 223,194
  • 41
  • 299
  • 337