PHP/MySQL 插入空值
我正在从 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 列,它们可能为空,也可能不为空
I am reading from 1 table, changing some fields then writing to another table, nothing happens if inserting and one of the array values is null when I would like it to insert null in the database (null values are allowed for the field). It looks a bit like this:
$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']});
}
Not every row has a null value and in my query there are more fields and 2 columns which may or may not be null
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个使用准备好的语句确实可以帮您省去一些麻烦的例子。
在 MySQL 中,为了插入空值,您必须在 INSERT 时指定它,或者将该字段保留在外面,这需要额外的分支:
但是,如果您想在该字段中插入值,则必须现在分支您的代码以添加单引号:
准备好的语句会自动为您执行此操作。他们知道
string(0) ""
和null
之间的区别,并正确编写您的查询:它会为您转义您的字段,确保您不会忘记绑定一个参数。没有理由继续使用
mysql
扩展。使用mysqli
,它是准备好的语句。你将为自己节省一个痛苦的世界。This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at
INSERT
time or leave the field out which requires additional branching:However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
Prepared statements automatically do that for you. They know the difference between
string(0) ""
andnull
and write your query appropriately:It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the
mysql
extension. Usemysqli
and it's prepared statements instead. You'll save yourself a world of pain.对于可接受
NULL
的字段,您可以使用var_export($var, true)
输出string
、integer
或NULL
文字。请注意,您不会用引号将输出括起来,因为它们会自动添加或省略。例如:
For fields where
NULL
is acceptable, you could usevar_export($var, true)
to output thestring
,integer
, orNULL
literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.For example: