Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

php - MySQL, how to insert null dates

I am having trouble inserting null values into date fields into a MySQL table.

Here is the insert query:

$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ("'.$string1.'", "'.$string2.'", '.$date1.', '.$date2.')';

Columns s1 and s2 take string values and d1 and d2 take dates. When I run this query with only the string fields, there is no problem.

The date values can be either set or null, so I have not included the quotation marks in the query, but have instead added them to the variable earlier on. This is the php code I am using to set the date values:

if (empty($date1)){
    $date1 = NULL;
}
else{
    $date1part = explode("/",$date1);
    $date1 = '"'.$date1part[2].'/'.$date1part[1].'/'.$date1part[0].'"';
}

When the date values are all set, the record is inserted correctly. However, when either of the dates is null, nothing is inserted.

Why can't I just insert null values into MySQL like this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

$query = "INSERT INTO table (column_s1, column_s2, column_d1, column_d2) 
          VALUES ('$string1', '$string2', " . ($date1==NULL ? "NULL" : "'$date1'") . ", " . ($date2==NULL ? "NULL" : "'$date2'") . ");";

so for example if you put this into query:

$string1 = "s1";
$string2 = "s2";
$date1 = NULL;
$date2 = NULL;

result should be:

INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...