I’m having a helluva time figuring this one out – it seems to be a well documented question, but none of the solutions go quite far enough to completely solve my problem.
Basically I’ve got a database for our website that saves upcoming events; occasionally these events have more than one showing, so we have fields where we can put in these dates if it does. Most of the time, there’s just one date to put in, so our extra date fields (date2, date 3, etc) are blank. If they’re blank, I want them to be saved to the mysql database as NULL.
An example of what I’ve got for tossing the values to mySQL looks like this:
if (empty($_POST['date2']))
{$date2 = NULL;
}
else
{$date2 = mysql_real_escape_string(date("Y-m-d",strtotime($_POST['date2'])));
}
Which is doing what it’s supposed to. The problem comes when we try to update the variable as follows:
mysql_query("UPDATE events
SET date2='".mysql_real_escape_string($date2))."',
mySQL doesn’t know what this value is (obviously, because you can’t escape string or format a date on NULL) so it saves the value as 0000-00-00 instead (or 1969-12-31…depending on my attempt to fix the problem). What I can’t figure out is how to input a value for date2 without using ”s.
I tried changing it to date2 = $date2, But the code won’t execute and tosses up an error. date2=’$date2′, executes – but again it’s not saving NULL correctly (I think because it’s saving ‘NULL’ and not NULL?).
Any advice?
You have the variable in single quotes:
Which means you are trying to save a string to the field.
If you want it to be
nullyou need to drop the quotes around it.Edit: Why not pop it directly into the
ifstatement right off the bat?Updated code:
On that note, if you are writing this code nice and fresh, you might want to consider starting with PDO. and using prepared statements.