SQLSRV PHP插入问题与日期时间转换

问题描述

当我尝试放置日期时,在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);
...

?>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...