简体   繁体   English

空值SQL Server和PHP

[英]Null value SQL Server and PHP

Hi there I have a question about Null values. 嗨,我有一个关于空值的问题。

Basically I have a bunch of variables and I would like to do a bunch of checks then add values at the end however some of these values will need to be NULL. 基本上,我有一堆变量,我想做一堆检查,然后在最后添加值,但是其中一些值需要为NULL。

so for example if a value is not set I would like to set the value of the variable to null so that it will not put anything in when I insert to the database. 因此,例如,如果未设置值,则要将变量的值设置为null,以便在插入数据库时​​不会放入任何内容。

$sql = "INSERT into specified table the values (?, ?,?)":
$params = "$param1, $NULLVALUEparam2, $param3);

so basically the same query will be executed each time but some input from the form are allowed to be left empty, how do I add these as NULL? 因此基本上每次都会执行相同的查询,但是允许将表单中的某些输入留空,如何将它们添加为NULL?

back story I am creating a registration page and some information is not required. 背景信息我正在创建注册页面,不需要某些信息。 the values are being sent via method POST to this action page where they are added to the database. 值通过方法POST发送到此操作页面,并在其中添加到数据库中。

Am I going about this wrong, is there a better way? 我要解决这个错误,是否有更好的方法? Thanks in advance. 提前致谢。

If you want to insert NULL into a specific column in a row you use the keyword NULL 如果要将NULL插入行中的特定列,请使用关键字NULL

INSERT INTO yourtable (id, created_at, string, string1)
VALUES (NEWID(), GETDATE(), 'your string you have', NULL)

This inserts a row and place it as NULL. 这将插入一行并将其放置为NULL。

If you don't have a value for a specific column you don't even need to insert it, then you just skip it. 如果您没有特定列的值,甚至不需要插入它,则只需跳过它。

INSERT INTO yourtable (id, created_at, string)
VALUES (NEWID(), GETDATE(), 'your string you have')

This will add a row and leave the string1 column NULL. 这将添加一行并将string1列保留为NULL。 But then, of course, your column must allow NULL values in both circumstances. 但是,当然,在两种情况下,您的列都必须允许NULL值。

So your code should skip the column OR just write NULL as string when you build your sql statement that you execute after. 因此,在构建之后执行的sql语句时,您的代码应跳过该列,或者仅将NULL作为字符串写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM