178

I want a value to be set to NULL if nothing is put into the text box in the form I'm submitting. How can I make this happen? I've tried inserting 'NULL' but this just adds the word NULL into the field.

I'm not sure what code I should provide for this, I'm just writing an UPDATE query.

1
  • 13
    You'll have to insert the word null without the quotes.. Commented Feb 16, 2012 at 15:50

10 Answers 10

342

Don't put NULL inside quotes in your update statement. This should work:

UPDATE table SET field = NULL WHERE something = something 
Sign up to request clarification or add additional context in comments.

Comments

24

You're probably quoting 'NULL'. NULL is a reserved word in MySQL, and can be inserted/updated without quotes:

INSERT INTO user (name, something_optional) VALUES ("Joe", NULL); UPDATE user SET something_optional = NULL; 

Comments

12
UPDATE MyTable SET MyField = NULL WHERE MyField = '' 

2 Comments

I think that the problem is that he's using: 'NULL' instead of NULL.
But, with some care, this could fix existing wanna-be-null empty fields :P
8

You should insert null, not the string of 'NULL'.

Comments

6

Use NULL (without the quotes around it).

UPDATE users SET password = NULL where ID = 4 

Comments

6
if (($_POST['nullfield'] == 'NULL') || ($_POST['nullfield'] == '')) { $val = 'NULL'; } else { $val = "'" . mysql_real_escape_string($_POST['nullfield']) . "'"; } $sql = "INSERT INTO .... VALUES ($val)"; 

if you put 'NULL' into your query, then you're just inserting a 4-character string. Without the quotes, NULL is the actual null value.

Comments

3

Assuming the column allows a null setting,

$mycolupdate = null; // no quotes 

should do the trick

1 Comment

... assuming that you don't cast $mycolupdate to string at a later stage.
3

The answers given here are good but i was still struggling to post NULL and not zero in mysql table.

Finally i noted the problem was in the insert query that i was using

 $quantity= "NULL"; $itemname = "TEST"; 

So far so good.

My insert query was bad.

 mysql_query("INSERT INTO products(quantity,itemname) VALUES ('$quantity','$itemname')"); 

I corrected query to read.

 mysql_query("INSERT INTO products(quantity,itemname) VALUES ('".$quantity."','$itemname')"); 

So the $quantity is outside of the main string. My sql table now accepted to record null quantity instead of 0

1 Comment

I would also recommend abandoning the deprecated mysql_ functions and switch to mysqli or, my preference, PDO.
2

The problem you had is most likely because mysql differentiates between null written in capital letters and null written in small case.

So if you used an update statement with null, it would not work. If you set it to NULL, it would work fine.

Thanks.

Comments

-1

right click on it and choose "clear field content"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.