0

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.

4
  • I'm pretty sure the code you posted won't work, but it's also unclear how you're using it. Can you provide a sample of code you've tried? Generally, you just have to marshall your parameters and insert null wherever you didn't get a response. Commented Apr 26, 2012 at 22:38
  • Shouldn't $params be an array? Commented Apr 26, 2012 at 22:41
  • it will be an array I don't have any code at the moment I am working through theory at the moment. My question is can you insert a NULL value and can you set a value of a parameter as NULL? Commented Apr 26, 2012 at 23:11
  • Do you mean to use PDO? If it's so then the question is the same as <stackoverflow.com/questions/1391777/…> Commented Apr 27, 2012 at 1:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.