0

Hey guys it may have been asked before but I am still stuck with a peculiar issue.

I am trying to Pass a dateTime object to my mysql insert statement but it always tells me there is an error namely:

Object of class DateTime could not be converted to string

$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>";

Where $dateToPass is a datetime field in my database.

Hope you guys can help.

3
  • remove the comment and it should be $dateToPass = $dateToPass->format('Y-m-d H:i:s'); Commented Apr 11, 2017 at 2:38
  • tried that all it does say that it could not convert the date to specified format. Commented Apr 11, 2017 at 2:40
  • Guys I figured it out apparently the $date I was passing in the query had to be a string but it was a date object Commented Apr 11, 2017 at 2:44

1 Answer 1

2

you cannot send DateTime object as string. Try converting it to string as MySQL expects.

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

Alternatively if you are always going to store current datetime you can use the MySQL NOW() like

$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');";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.