apk*_*ith 11 php mysql null date
我在将日期字段中的空值插入MySQL表时遇到问题.
这是插入查询:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ("'.$string1.'", "'.$string2.'", '.$date1.', '.$date2.')';
Run Code Online (Sandbox Code Playgroud)
列s1和s2采用字符串值,d1和d2采用日期.当我只使用字符串字段运行此查询时,没有问题.
日期值可以设置为null或null,因此我没有在查询中包含引号,而是在之前将它们添加到变量中.这是我用来设置日期值的PHP代码:
if (empty($date1)){
$date1 = NULL;
}
else{
$date1part = explode("/",$date1);
$date1 = '"'.$date1part[2].'/'.$date1part[1].'/'.$date1part[0].'"';
}
Run Code Online (Sandbox Code Playgroud)
全部设置日期值后,将正确插入记录.但是,当任一日期为空时,不会插入任何内容.
为什么我不能像这样只将空值插入MySQL?
试试这个:
$query = "INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ('$string1', '$string2', " . ($date1==NULL ? "NULL" : "'$date1'") . ", " . ($date2==NULL ? "NULL" : "'$date2'") . ");";
Run Code Online (Sandbox Code Playgroud)
例如,如果你把它放入查询中:
$string1 = "s1";
$string2 = "s2";
$date1 = NULL;
$date2 = NULL;
Run Code Online (Sandbox Code Playgroud)
结果应该是:
INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL);
Run Code Online (Sandbox Code Playgroud)
您应该首先将null变量转换为NULL字符串,如下所示:
if(is_null($date1)){
$date1 = 'NULL';
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是MySQL日期列,则还必须指定在创建它时应保留null,如下所示:
CREATE TABLE `table` (
id INT NOT NULL AUTO_INCREMENT,
date DATE NULL DEFAULT NULL,
PRIMARY KEY(id)
)
Run Code Online (Sandbox Code Playgroud)
使用绑定参数执行查询也非常重要,例如使用pdo
像这样的东西:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES (?, ?, ?, ?)';
$stmt = $db->prepare($query);
$stmt->execute(array($string1,$string2,$date1,$date2));
Run Code Online (Sandbox Code Playgroud)
小智 2
反斜杠 N 是 MySQL 中表示 NULL 的另一种方式。
尝试将值(反斜杠 N):\N放入参数之一,如下所示:
$data1 = "\N";
$sql="insert into tablename set column_s1='" . $data1 .
"', column_s2='" . data2 .
"', column_s3='" . $data3 . "'";
Run Code Online (Sandbox Code Playgroud)
参考: http: //dev.mysql.com/doc/refman/5.1/en/load-data.html
| 归档时间: |
|
| 查看次数: |
44214 次 |
| 最近记录: |