0

On my page I have a few textboxes and two of those, first name and last name, are not required. If nothing is entered in one or both of those fields I need to insert NULL as nothing rather than NULL as a string value. Currently it is entering them as string values. What do I need to do so it inserts NULL values instead of a string?

PHP Code

<?php
// SQL connection and other variables...

if (!empty($_POST['firstname'])) {
    $firstname = $_POST['firstname'];
} else {
    $firstname = 'NULL';
}
if (!empty($_POST['lastname'])) {
    $lastname = $_POST['lastname'];
} else {
    $lastname = 'NULL';
}

$sp = "exec sp_test_proc '$street1', '$street2', '$firstname', '$lastname'";
$res = odbc_exec($conn, $sp);
?>

If I pass in NULL instead of the variable for either of the parameters it works fine. Not sure what is causing the issue by using a variable.

7
  • what if you just did $firstname = ''; and so on? Commented Jun 17, 2013 at 19:38
  • How about using a prepared statement to call your procedure and pass it a primitive value of null instead of a string that contains the word NULL. Commented Jun 17, 2013 at 19:39
  • 1
    @Fred then he would have a blank string, not NULL. Commented Jun 17, 2013 at 19:39
  • @Jessica Got it. I guess I had a bit of a hard time understanding the question. That 3rd cup of coffee hasn't quite kicked in yet! Commented Jun 17, 2013 at 19:41
  • 1
    Have a look at stackoverflow.com/questions/5329542/… Commented Jun 17, 2013 at 19:52

2 Answers 2

3

Write NULL instead of 'NULL'

You're making it a string by using quotes.

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

1 Comment

This is correct, thank you for the help @Jessica I really appreciate it.
1

You need to pass NULL as unquoted string. This is because you are building plain SQL. So make sure the statement is valid one.

For parameterized query it should be NULL value instead of NULL string.

3 Comments

Not to be rude but you're saying the same thing. For plain SQL OR a prepare statement with parameters you would use NULL not 'NULL'
Well I meant null value = $var=null; and null string = $var='null';. But I agree there was no formatting as its quite hard in cell phone.
It has nothing to do with the formatting - you are saying do X for plain SQL and do X for parameter. My point is it doesn't matter which he is doing, because both require X. Your answer is confusing because of that.

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.