传递给PHP的插入查询的日期时间不起作用

时间:2017-04-11 02:36:09

标签: php mysql

嘿,伙计们之前可能会被问过,但我仍然遇到一个特殊的问题。

我试图将一个dateTime对象传递给我的mysql插入语句,但它总是告诉我有一个错误:

  

类DateTime的对象无法转换为字符串

$dateToPass = new DateTime('now');
                        //$dateToPass = $dateToPass->format('d/m/Y H:i:s');
                        //inserting values
                        $SQLstring="Insert into Request(cust_num,request_date,item_description,item_weight,pickup_address,pickup_suburb,
                        pickup_date,pickup_time,receiver_name,delivery_address,delivery_suburb,delivery_state) 
                        values(27,$dateToPass,'$desc',$weight,'$address','$suburb','$date',                         '$time','$rname','$raddress','$rsuburb','$rstate');";
                        $queryResult = @mysqli_query($DBConnect, $SQLstring)
                        Or die ("<p>Unable to query the Customer table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";

$ dateToPass是我数据库中的日期时间字段。

希望你们能帮忙。

2 个答案:

答案 0 :(得分:2)

您无法将DateTime对象作为字符串发送。尝试将其转换为MySQL期望的字符串。

$dateToPass = new DateTime('now');
$dateToPass = $dateToPass->format('Y-m-d H:i:s');

或者,如果您总是要存储当前日期时间,则可以使用MySQL NOW()之类的

$SQLstring="Insert into Request(cust_num,request_date,item_description,item_weight,pickup_address,pickup_suburb,
pickup_date,pickup_time, receiver_name,delivery_address,
delivery_suburb,delivery_state)  
values(27,NOW(),'$desc',$weight,'$address','$suburb','$date', '$time','$rname','$raddress','$rsuburb','$rstate');";

答案 1 :(得分:0)

您必须将变量转换为字符串,或使用以下代码

$dateToPass = date('Y-m-d H:i:s');