PHP MYSQL列数不匹配

时间:2014-12-02 19:27:48

标签: php html mysql database

尝试将POST数据作为新记录插入mysql数据库。表有5列:

ContractorID,firstName,lastName,email,password

$insert = "INSERT INTO CONTRACTOR (firstName, lastName, email, password)
VALUES ($firstName, $lastName, $email, $password)";

if (mysqli_query($conn, $insert)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $insert . "<br>" . mysqli_error($conn);
}

ContractorID是一个自动增量主键,所以我想我可以将其从插入中删除。但是,即使我改为:

$insert = "INSERT INTO CONTRACTOR (ContractorID, firstName, lastName, email, password)
VALUES ('DEFAULT', '$firstName', '$lastName', '$email', '$password')";

我得到同样的错误:

错误:INSERT INTO CONTRACTOR(firstName,lastName,email,password)VALUES(&#39; w4rwsfsdf&#39;,&#39; wqerwerw&#39;,&#39; rweqrqwer&#39;&#39; qwerqwer& #39) 列数与第1行的值计数不匹配

编辑:这是一个缺少逗号导致问题,我在这里错误地复制了代码错误消息。无法将linux复制并粘贴到Windows。

1 个答案:

答案 0 :(得分:2)

根据您的originally posted question添加缺少的逗号,而不是将其标记为“编辑”。

您的VALUES中缺少逗号

VALUES ('DEFAULT' '$firstName'
                 ^ right there

将其更改为:

VALUES ('DEFAULT', '$firstName'

修改

如果可以的话,我建议您删除/删除当前的表格,并运行以下内容:

$sql = "CREATE TABLE IF NOT EXISTS CONTRACTOR
(
  `ContractorID` int(10) NOT NULL AUTO_INCREMENT,
  `firstName` varchar(55) DEFAULT NULL,
  `lastName` varchar(55) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
   PRIMARY KEY (`ContractorID`)

            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

INSERT INTO CONTRACTOR (firstName, lastName, email, password)
VALUES ('John', 'Doe', 'email@example.com', 'test_password')";

if (mysqli_query($conn, $sql)) {
    echo "New table created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

然后再次尝试查询。

$insert = "INSERT INTO CONTRACTOR (firstName, lastName, email, password)
VALUES ('Bob', 'Smith', 'email_2@example.com', 'test_password_2')";

if (mysqli_query($conn, $insert)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $insert . "<br>" . mysqli_error($conn);
}