简体   繁体   English

PHP PDO将字符串转换为MS SQL datetime2

[英]PHP PDO convert string to MS SQL datetime2


I have issues with converting my string into a valid datetime2 for use in a MS SQL DB. 将字符串转换为有效的datetime2以在MS SQL DB中使用时遇到问题。 I am using the CAST operator from SQL to convert it into a valid format. 我正在使用SQL的CAST运算符将其转换为有效格式。 The Code looks like this: 该代码如下所示:

include("sqlconnection.php");
$statement = $pdo->prepare("UPDATE auftrag SET bestelldatum = CAST(:bestelldatum AS datetime(7)), lieferdatum_wunsch = :lieferdatum, fk_id_kunde = (Select id_kunde from kunde where firmenname = :kunde), fk_id_auftragsstatus = (SELECT id_auftragsstatus from auftragsstatus WHERE bezeichnung = :status) WHERE id_auftrag = :id");
$result = $statement->execute(array("bestelldatum" => $_POST['bestelldatum'], "lieferdatum" => $_POST['lieferdatum'], "kunde" => $_POST['kunde'], "status" => $_POST['status'], "id" => $_POST['id']));
echo $result;

The format of the $_POST['bestelldatum'] looks like this: dd/mm/yyyy $ _POST ['bestelldatum']的格式如下:dd / mm / yyyy
I get the following error: 我收到以下错误:

Uncaught PDOException: SQLSTATE[42000]: 
[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]CAST oder CONVERT: Für 
den datetime-Typ wurden ungültige Attribute angegeben. in 
C:\xampp\htdocs\php\scripts\scripts.php:402 Stack trace: #0 
C:\xampp\htdocs\php\scripts\scripts.php(402): PDOStatement->execute(Array) #1 
C:\xampp\htdocs\php\scripts\scripts.php(30): saveAuftragChanges() #2 {main} 
thrown in C:\xampp\htdocs\php\scripts\scripts.php on line 402

Translated: cast or convert invalid attributes specified for type 'datetime' 翻译:转换或转换为类型'datetime'指定的无效属性

I hope you can help me, 我希望你能帮帮我,
Sincerly, 诚恳,
Jan 一月

The strtotime function expects a date with slashes to be in US format (mm/dd/yyyy) but your date is in European format so it first needs to have the slashes changed to dashes. strtotime函数期望带斜杠的日期为美国格式(mm / dd / yyyy),但您的日期为欧洲格式,因此首先需要将斜杠更改为破折号。 Use the following to format your date for SQL. 使用以下命令格式化SQL日期。

$bestelldatum = date('Y-m-d',strtotime(str_replace('/','-',$_POST['bestelldatum'])));

If a time is needed too try this instead (only change is to add a valid time to the variable created). 如果还需要时间,请尝试使用此时间(唯一的变化是在创建的变量中添加有效时间)。

$bestelldatum = date('Y-m-d 00:00:01',strtotime(str_replace('/','-',$_POST['bestelldatum'])));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM