MySQL - 如何插入可能为空的值
我在 PHP 脚本中有一些值,必须将它们插入到 MySQL 表中。例如,这里有 3 个日期 d1
、d2
和 d3
。
我有默认语句将值插入数据库:
insert into mytable set a=1, b=2, d1='$val', d2='$val2', d3='$val3'
是否有一种非常简单的方法可以编写 SQL 语句来插入 d1、d2 和 d3 NULL 值而不是日期(如果一个(或多个)$) val1
、$val2
和 $val3
是 nil 吗?无需处理新的 PHP 变量?
I have some values in a PHP script that I must insert in a MySQL table. Here is for example 3 dates d1
, d2
, and d3
.
I have that default statement to insert the values into the database:
insert into mytable set a=1, b=2, d1='$val', d2='$val2', d3='$val3'
Is there a very simple way I can write the SQL statement to insert into d1, d2 and d3 NULL values instead of a date if one (or more) of $val1
, $val2
and $val3
is nil ? Without having to deal with new PHP variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您将所有内容都放在
$data
数组中:该字符串将包含例如。如果数组中的值不存在或等于
null
,则用d2=NULL
代替d2='xyz'
。您还必须确保要粘贴到查询中的字符串已正确清理(例如,使用
mysql_real_escape_string()
)。 我的答案将您的变量视为已经准备好并已清理,因为您只想知道如何插入NULL
值而不是您拥有的变量。因为问题只是关于根据变量的值在查询中输入 NULL 值,所以我认为在这里详细讨论清理不是一个好主意。您可以在此处找到有关 SQL 注入以及如何在 PHP 中防止 SQL 注入的更多详细信息:在 PHP 中停止 SQL 注入的最佳方法。祝你好运! :)
Assuming you have it all in
$data
array:The string will contain eg.
d2=NULL
instead ofd2='xyz'
, if the value in array does not exist or is equal tonull
.You have to also make sure that the strings you want to paste into the query are properly sanitized (eg. using
mysql_real_escape_string()
). My answer treats your variables as already prepared and sanitized, as you only wanted to know how to insertNULL
values instead of the variables you have.Because the question was only about entering
NULL
values in the query based on the value of variables, I do not think discussing sanitization in detail here would be a good idea. You can find a lot more detailed info on SQL Injection and how to prevent it in PHP here: Best way to stop SQL Injection in PHP. Good luck! :)可能有更好的方法来做到这一点,但如果所有其他方法都失败了,您可以对每个值执行此操作:
然后将 PHP 查询字符串更改为:
您应该考虑使用 准备好的语句 和
PDO
而不是构建这样的查询字符串,特别是当变量中涉及用户输入时。There's probably a better way to do this, but if all else fails, you can do this with each of your values:
Then change your PHP query string to this:
You should consider using prepared statements and
PDO
instead of building a query string like that, especially if there is user input involved in your variables.最简单的事情是定义
This 并确保查询的完整性。
The simplest thing would be to define
This as well ensures integrity of your queries.
我发现这种方式是做我想做的事情的最简单的方式:
I found that way to be the simpliest way to do what I wanted to do: