0

Since years I've a simple question: How to set values to NULL and write NULL to MySQL?

$var = trim(mysqli_real_escape_string($_POST["input_from_user"]));
if(strlen($var) < 1) {
$newvar = NULL;
}
else {
$newvar = $var;
}

and:

INSERT INTO `table` (`var`) VALUES ('$newvar')

...alyways writes an empty value into MySQL-Table, but not NULL! Of course: The field "var" is declared to allow "NULL" in MySQL.

3
  • try to use unset Commented Oct 15, 2015 at 11:32
  • Five downvoted answers, what a question. Commented Oct 15, 2015 at 11:50
  • @AlanMachado one of them actually answers the question but not everyone sees it right away. Commented Oct 15, 2015 at 11:56

3 Answers 3

1

With PDO you can use bindValue() method to prepared statement

bindValue(':param', null, PDO::PARAM_INT);

Here you can find how to do it in mysqli

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

Comments

-3

You have to use prepared statements for all your database interactions in the first place. When used, they will deliver your NULL value to database all right, either with mysqli and PDO.

Comments

-3

Try with

"INSERT INTO `table` (`var`) VALUES (" . (is_null($newvar)) ? "NULL" : $newvar . ")";

6 Comments

That's bad in so many ways.
"NULL" != NULL my friend
and that's why it works my friend. It is there to be seen by the query parser not the php variable
@JulioSoares it took me a while to see that this actually works. Too bad that almost no-one can bring up the attention span to also see it. I recommend you approve my edit so that everyone can see that this actually works. Even though Robert was wrong, you should not revenge-downvote, ever.
@Robert the quotes are around the string NULL, these quotes won't appear in the query string. This answer actually is the most simple and correct.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.