【问题标题】:SQLSRV PHP Insert Problem with datetime conversion日期时间转换的 SQLSRV PHP 插入问题
【发布时间】:2020-09-14 06:14:45
【问题描述】:

我在尝试输入日期时在 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提供的日期字符串转换为日期时间:

选项 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);

但是没有一个选项可以解决问题...你能帮帮我吗?

谢谢!!

【问题讨论】:

  • 提供样品$order->get_date_created();
  • 我正在尝试所有这些方法,因为直接使用它不起作用
  • 不,我是说你能举一个$order->get_date_created();的例子
  • @josesd $newformat 的实际值是多少 - PHP DateTime 对象或字符串,表示日期时间值?您使用的是 Micorosft SQL Server(sqlsrv 标签是关于 SQL服务器)?
  • $order->get_date_crated();返回 2020-09-14T05:21:42+00:00,我读过它,我认为它的格式正确,但它返回错误

标签: php sql-server datetime sqlsrv


【解决方案1】:

当您将日期\时间值作为文本传递给 SQL Server 中的datetime 列时,您需要使用明确的日期\时间格式 (yyyy-mm-ddThh:mm:ss)。

函数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);
...

?>

【讨论】:

    猜你喜欢
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 2021-04-30
    • 1970-01-01
    相关资源
    最近更新 更多