首页  >  文章  >  后端开发  >  为什么我的 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