首頁  >  文章  >  後端開發  >  為什麼我的 PHP 和 MySQL 程式碼中出現「列計數與第 1 行的值計數不符」錯誤?

為什麼我的 PHP 和 MySQL 程式碼中出現「列計數與第 1 行的值計數不符」錯誤?

Barbara Streisand
Barbara Streisand原創
2024-10-27 11:23:01755瀏覽

Why am I getting the

修正PHP 和MySQL 中的「列計數與第1 行的值計數不符」錯誤

嘗試將資料插入使用PHP 的MySQL 資料庫,您可能會遇到以下錯誤:

Column count doesn't match value count at row 1

當INSERT 查詢中提供的值的數量與目標表中定義的列數不符時,就會出現此錯誤。

了解原因

在範例程式碼中,您在INSERT 查詢中指定了9 欄位:

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username)

但是,您只提供了8 個值:

sprintf("INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
    mysql_real_escape_string($name),
    mysql_real_escape_string($description),
    mysql_real_escape_string($shortDescription),
    mysql_real_escape_string($ingredients),
    //mysql_real_escape_string($image),
    mysql_real_escape_string($length),
    mysql_real_escape_string($dateAdded),
    mysql_real_escape_string($username));

因此,MySQL 無法將提供的值的數量與指定列匹配,從而導致錯誤。

解決方案:確保值計數與列符合Count

要解決此問題,您需要確保查詢中的值數與目標表中的列數相符。在這種情況下,您錯過了提供 Method 值。

修改您的程式碼以包含缺少的值:

$query = sprintf("INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
    mysql_real_escape_string($name),
    mysql_real_escape_string($description),
    mysql_real_escape_string($shortDescription),
    mysql_real_escape_string($ingredients),
    mysql_real_escape_string($method),
    mysql_real_escape_string($length),
    mysql_real_escape_string($dateAdded),
    mysql_real_escape_string($username));

透過提供正確數量的值,您將能夠成功向MySQL資料庫插入數據,不會遇到列數不匹配錯誤。

以上是為什麼我的 PHP 和 MySQL 程式碼中出現「列計數與第 1 行的值計數不符」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn