172

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.

Backlin
  • 14,612
  • 2
  • 49
  • 81
muttley91
  • 12,278
  • 33
  • 106
  • 160

10 Answers10

330

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

UPDATE table SET field = NULL WHERE something = something
Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
Fosco
  • 38,138
  • 7
  • 87
  • 101
22

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;
Andrew Ensley
  • 11,611
  • 16
  • 61
  • 73
11
UPDATE MyTable
SET MyField = NULL
WHERE MyField = ''
Bassam Mehanni
  • 14,796
  • 2
  • 33
  • 41
7

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

xdazz
  • 158,678
  • 38
  • 247
  • 274
6

Use NULL (without the quotes around it).

UPDATE users SET password = NULL where ID = 4
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
3

Assuming the column allows a null setting,

$mycolupdate = null; // no quotes

should do the trick

Mr Griever
  • 4,014
  • 3
  • 23
  • 41
2

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

webs
  • 528
  • 5
  • 11
  • I would also recommend abandoning the deprecated mysql_ functions and switch to mysqli or, my preference, PDO. – muttley91 May 02 '15 at 22:30
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.

-1

right click on it and choose "clear field content"