PHP/MySQL 插入空值

问题描述 投票:0回答:2

我正在从 1 个表中读取数据,更改一些字段,然后写入另一个表,当我希望在数据库中插入 null 时(该字段允许使用 null 值),如果插入并且其中一个数组值为 null,则不会发生任何情况。看起来有点像这样:

$results = mysql_query("select * from mytable");
while ($row = mysql_fetch_assoc($results) {
    mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', {$row['null_field']});
}

并非每一行都有空值,并且在我的查询中还有更多字段和 2 列可能为空也可能不为空

php mysql insert null
2个回答
70
投票

这是一个使用 prepared statements 确实为您省去了一些麻烦的示例。

在 MySQL 中,为了插入空值,您必须在

INSERT
时指定它,或者忽略需要额外分支的字段:

INSERT INTO table2 (f1, f2)
  VALUES ('String Value', NULL);

但是,如果您想在该字段中插入值,您现在必须分支代码以添加单引号:

INSERT INTO table2 (f1, f2)
  VALUES ('String Value', 'String Value');

准备好的报表会自动为您完成此操作。他们知道

string(0) ""
null
之间的区别并正确地编写您的查询:

$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);

$field1 = "String Value";
$field2 = null;

$stmt->execute();

它会为您转义字段,确保您不会忘记绑定参数。没有理由继续使用

mysql
扩展。使用
mysqli
和它的 prepared statements 来代替。你将为自己节省一个痛苦的世界。


4
投票

对于可接受

NULL
的字段,您可以使用
var_export($var, true)
输出
string
integer
NULL
文字。 请注意,您不会用引号括住输出,因为它们会自动添加或省略。

例如:

mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.