簡體   English   中英

PHP將數組值插入MySQL預處理語句

[英]PHP Inserting array values into MySQL prepared statement

我有一個值數組,我試圖插入到數據庫中。 目前,下面只插入數組中的第一個鍵值對,然后返回錯誤:

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

functions.php中的第33行是在這個函數中

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

    return $results ? $results : false;
}

主要代碼是

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";
    }
}

所以我將OK連接到DB(代碼中的其他位置),並且第一個鍵值對已成功插入,但不是數組的其余部分。 我猜我的語法在某處不正確

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

但我無法弄清楚。 任何幫助非常感謝!

INSERT后不應該fetchAll() INSERT沒有結果集。

我剛剛運行了一個插入測試,然后在PDOStatement對象上調用fetchAll() ,我確認這會導致你顯示的“常規錯誤”異常。

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

拋出:

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

您的值數組不正確。 鑰匙也需要:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM