0

我正在尝试将变量设置为NULL

$q = NULL.",";
$q .= 'abc';

并保存到数据库中:

mysql_query("INSERT INTO table (col_a, col_b) VALUES (".$q.")")

但这会产生错误消息:

INSERT INTO table (col_a, col_b) VALUES (,'abc')You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ','abc')' at line 2

如何NULL从变量保存到数据库中?

4

4 回答 4

5

you can get rid of the column where you want its value to be null, eg

$q = 'abc';
mysql_query("INSERT INTO table (col_b) VALUES ($q)")

or if value is dynamic, the only problem with your current code is that you haven't include NULL in your string,

$q = "NULL,";
$q .= "'abc'";
mysql_query("INSERT INTO table (col_a, col_b) VALUES ($q)")

the your code is vulnerable with SQL Injection, please read the article below to learn how to prevent from it.

于 2012-12-25T01:33:58.027 回答
2

You're concatenating NULL and trying to parse it, which in the statement, would actually read:

, abc

Instead of the expected

NULL, abc

So just write a literal "NULL" in your statement.

于 2012-12-25T01:34:40.663 回答
2

Pass the literal, unquoted string inside the query:

$q = "NULL,";
于 2012-12-25T01:35:03.777 回答
2
$q = "NULL,";
$q .= '"abc"';

Gives you NULL,"abc" which you can include in your query.

The error you posted couldn't have come from the code in the question.. where did the quotes around abc come from? You need to enclose it in quotes inside the quotes for the php variable for them to show up in the SQL too.

于 2012-12-25T01:35:16.853 回答