简体   繁体   中英

NULL date value from a PHP Variable to MySQL

Im working in joomla and having problems to store NULL date value instead of 0000-00-00 when it's not setted. In MySql table the date field is setted with default value NULL and the null checkbox is checked. I tried all the suggestion that I found here but with no luck.

here my variable for the date:

if (isset($fbpage['endTime'])): 
$fbdataE = (new DateTime($fbpage['endTime']))->format('Y-m-d'); 
else : $fbdataE = NULL ; endif;

and here my code to store in MySql

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$columns = array(
'whateverelse',
'enddates',
'whateverelse'
);
$values = array(
$db->quote($whateverelse),
$db->quote($fbdataE),
$db->quote($whateverelse)
);
$query
->insert($db->quoteName('#__table'))
->columns($db->quoteName($columns))
->values(implode(',', $values));

$db->setQuery($query);
$db->execute();

Any suggestion?

Thank's in advance.

Thank.s to @PaulSpiege and to @GabrielHeming that given me a start point, I found a solution.

In effect ->quote() create a quoted string ' ' and NULL must to be stored in MySql unquoted, so, for who feel lost on this, like I was, here is the solution:

1) I changed NULL into a quoted string 'NULL' in the date's condition

if (isset($fbpage['endTime'])): 
$fbdataE = (new DateTime($fbpage['endTime']))->format('Y-m-d'); 
else : $fbdataE = 'NULL' ; endif;

2) I added a new condition to quote if is a valid date and unquote if it is not

if($fbdataE !='NULL'):
$fbdataE = $db->quote($fbdataE); 
else:
$fbdataE = $db->escape($fbdataE);
endif;

3) and, of course, I putted only the variable in the values array

$values = array(
$db->quote($whateverelse),
$fbdataE,
$db->quote($whateverelse)
);

that's it !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM