Reputation: 180
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.
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.
$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?
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.
Am I going about this wrong, is there a better way? Thanks in advance.
Upvotes: 0
Views: 3627
Reputation: 6232
If you want to insert NULL into a specific column in a row you use the keyword 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.
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. But then, of course, your column must allow NULL values in both circumstances.
So your code should skip the column OR just write NULL as string when you build your sql statement that you execute after.
Upvotes: 1