Forum Moderators: coopster

Message Too Old, No Replies

inserting NULL to mysql db field with a php variable

         

snehula

10:18 am on Sep 12, 2011 (gmt 0)

10+ Year Member



Hi there,

I was trying to insert null into my database with a php variable set to "NULL", but this sets the field to the string "NULL" and not to the actual NULL value.
I'm updating the field value depending on user input (textbox), I'm testing this input for empty string and setting it to the string "NULL" in case it is empty.So my query goes like:
$sql = "UPDATE blabla SET whatever = '".$myvar."', whichever='".$othervar."' WHERE idBla= '".$somenumber.'";

I wonder if I should set $myvar or $othervar to the php NULL value like
$myvar = NULL;
instead of
$myvar = "NULL";

and would that be compatible with the mysql NULL value(while enclosing $myvar in single quotes in the query string)?
Or is it better to just conditionally build the query string and avoid all this confusion this way?

All in all, I'm just generally curious about how to best handle this situation and how does php null relate to mysql null :-)

penders

11:09 am on Sep 12, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Setting $myvar to "NULL" (a string) is correct, except your SQL statement should not surround this in single quotes. NULL is a special value in SQL, it is not a string.

The minor aggravation with this is that when $myvar is some other value then it should be surrounded by single quotes in the SQL. So you might want to make the single quotes part of $myvar itself.

snehula

11:18 am on Sep 12, 2011 (gmt 0)

10+ Year Member



lovely thanks :-)