deucalion0
deucalion0

Reputation: 2440

How to retrieve date from SQL server datetime column and store in php variable?

I am trying to retrieve the date only from my table and store it in a php variable so I can echo it out where and when I want. Here is how I am trying to do this:

$query3 = "select o.orderID,
o.orderDate

from orders o
join order_items i on o.orderID = i.orderID
where o.customerID = '" . $customerID . "'";

    $result3 = sqlsrv_query( $conn, $query3, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));

if( $result3 === false)
{
    echo "Error in query preparation/execution.\n";
    die( print_r( sqlsrv_errors(), true));
}

     while( $row = sqlsrv_fetch_array ( $result3, SQLSRV_FETCH_ASSOC))
    {
        $data1 = $row['orderDate']; 
    }

echo $data1;

I have experimented with the date() method and I can get a date on the screen but not a specific one selected from the database. Do I need to convert this before I echo it?

The error I am getting is this:

Catchable fatal error: Object of class DateTime could not be converted to string

Thank you.

Upvotes: 0

Views: 2926

Answers (2)

Álvaro González
Álvaro González

Reputation: 146460

You already have a DateTime object, as the error message suggests:

Catchable fatal error: Object of class DateTime could not be converted to string
                       ^^^^^^^^^^^^^^^^^^^^^^^^

That's a native PHP variable with a date. The driver does it for you!

Upvotes: 1

BugFinder
BugFinder

Reputation: 17858

Your code

     while( $row = sqlsrv_fetch_array ( $result3, SQLSRV_FETCH_ASSOC)) 
    { 
        $data1 = $row['orderDate'];  
    } 

echo $data1; 

works through each line of your result, but will only show if relevant the last one. Is this perhaps your issue?

Upvotes: 1

Related Questions