Set value to NULL in MySQL
MysqlSqlMysql Problem Overview
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.
Mysql Solutions
Solution 1 - Mysql
Don't put NULL
inside quotes in your update statement. This should work:
UPDATE table SET field = NULL WHERE something = something
Solution 2 - Mysql
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;
Solution 3 - Mysql
UPDATE MyTable
SET MyField = NULL
WHERE MyField = ''
Solution 4 - Mysql
You should insert null
, not the string of 'NULL'
.
Solution 5 - Mysql
Use NULL
(without the quotes around it).
UPDATE users SET password = NULL where ID = 4
Solution 6 - Mysql
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.
Solution 7 - Mysql
Assuming the column allows a null setting,
$mycolupdate = null; // no quotes
should do the trick
Solution 8 - Mysql
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
Solution 9 - Mysql
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.