php 使用 INSERT 将整数值插入 mysql int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11353345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting Integer value into mysql int using INSERT
提问by Fireworm
I'm trying to insert a new record in a MySQL database from PHP, which I've done a million times before, but for some reason, I can't get it to work this time, and it really bugs me.
我正在尝试从 PHP 在 MySQL 数据库中插入一条新记录,我之前已经做过一百万次了,但是由于某种原因,这次我无法让它工作,这真的让我很烦恼。
Inserting strings into all the varchar collumns are going great, but when I get to inserting a value into the int column, I get an error telling me that I have a syntax error.
将字符串插入到所有 varchar 列中效果很好,但是当我将一个值插入到 int 列中时,我收到一个错误消息,告诉我我有一个语法错误。
Basically, the first query works just fine, but the second one returns the error, and as you can see, I've made damn sure it really is an integer I'm trying to insert.
基本上,第一个查询工作正常,但第二个查询返回错误,正如您所看到的,我非常确定它确实是我要插入的整数。
I hope somebody can help. I'm really starting to develop a headache over this :/
我希望有人可以提供帮助。我真的开始为此头疼了:/
$groupId2 = 5;
$groupId = (int)$groupId2;
if(!mysqli_query($link, "INSERT INTO contestants (firstName, lastname, email) VALUES ('$firstName', '$lastName', '$email')"))
echo "First: " . mysqli_error($link);
if(!mysqli_query($link, "INSERT INTO contestants (firstName, lastname, email, group) VALUES ('$firstName', '$lastName', '$email', '$groupId')"))
echo "Second: " . mysqli_error($link);
回答by Musa
groupis a mysql keyword use back quotes around it
group是一个 mysql 关键字,在它周围使用反引号
"INSERT INTO contestants (firstName, lastname, email, `group`)
VALUES ('$firstName', '$lastName', '$email', '$groupId')"
回答by Jon Taylor
The error is because you surrounded your int with ' ', you need to get rid of your apostrophes and it will work just fine.
错误是因为你用 ' ' 包围了你的 int,你需要去掉你的撇号,它会工作得很好。
if(!mysqli_query($link,
"INSERT INTO contestants
(firstName, lastname, email, group) VALUES
('$firstName', '$lastName', '$email', $groupId)"))
^^^^^^^^^
To clarify, when inserting numerical fields you do not need them.
澄清一下,在插入数字字段时,您不需要它们。
According to pst this is wrong, although, the fact you do not need single quotes is still correct.
根据 pst 这是错误的,尽管您不需要单引号的事实仍然是正确的。

