问题描述
当我尝试放置日期时,在sql server数据库中执行插入查询时遇到问题。我的问题是:
从字符转换日期和/或时间时转换失败 日期时间插入字符串
我正在使用的查询是:
$sqlpedido = "INSERT INTO dbo.I_Pedido (id_cliente,Fecha,total,Comentario,portes,estado,FPago,id_destino,FormaEnvio) VALUES (?,?,?)";
$params = array($ClienteID,$newformat,$gtotal,$cusnote,$shiptotal,'0',$paymethod,$id_destino,$shipmethod);
$stmt26 = $conn5->prepare($sqlpedido);
$stmt26->execute($params);
变量$newformat
出现问题,我尝试了不同的形式将Woocommerce提供的日期字符串转换为datetime:
选项1:
$dcreated = $order->get_date_created();
$d = new DateTime($dcreated);
$timestamp = $d->getTimestamp();
$formatted_date = $d->format('c');
选项2:
$dcreated = $order->get_date_created();
$time = strtotime($dcreated);
$newformat = date('c',$time);
谢谢!
解决方法
当您将日期\时间值作为文本传递给SQL Server中的yyyy-mm-ddThh:mm:ss
列时,您需要使用明确的日期\时间格式(datetime
)。
函数get_date_created()
返回WooCommerce DateTime object,因此可以使用PHP DateTime::format方法设置值的格式:
<?php
...
$newformat = $order->get_date_created()->format('Y-m-d\TH:i:s');
$sqlpedido = "
INSERT INTO dbo.I_Pedido (id_cliente,Fecha,total,Comentario,portes,estado,FPago,id_destino,FormaEnvio)
VALUES (?,?,?)
";
$params = array($ClienteID,$newformat,$gtotal,$cusnote,$shiptotal,'0',$paymethod,$id_destino,$shipmethod);
$stmt26 = $conn5->prepare($sqlpedido);
$stmt26->execute($params);
...
?>