简体   繁体   中英

Getting date from SQL-Database creates error

I've been trying to get the calibration date from my SQL server database but it doesn't seem to work.

while($row = sqlsrv_fetch_array($result))  
{ 
$output .= "<tr><td>".$row['businessUnit']."</td><td>".
    $row['productGroup']."</td><td>".
    $row['deviceType']."</td><td>".
    $row['serialNumber']."</td><td>".    
    $row['location']."</td><td></td><td>".
    $row['condition']."</td><td>".
    $row['calibrationDate']."</td><td>".
    $row['itemDescription']."</td><td>
    <input type='checkbox'></input></td></tr>";  
}  
return $output;

If I do it like this I get this error: Object of class DateTime could not be converted to string

However when I try to format it like this:

$row['calibrationDate']->format('Y-m-d')

I get another error: Uncaught Error: Call to a member function format() on null

I have also tried to convert it to a new DateTime first:

$date = new DateTime($row['calibrationDate']);

Then I get: Uncaught TypeError: DateTime::__construct() expects parameter 1 to be string, object given

I don't know if it's relevant to the problem but not all columns have a date in that column. The datatype in the database is "date" and the format is "Ymd". How do I get the date to display?

you should used strtotime & date functions

$calibrationDate= strtotime($row['calibrationDate']);
echo date('Y-m-d H:i:s', $calibrationDate);

您可以像这样使用php strtotime()和date()函数

date('Y-m-d H:i:s',strtotime(($row['calibrationDate']))."</td><td>".

If you want to retrieve date and time types (datetime, date, time, datetime2, and datetimeoffset) as strings, you must set connection option ReturnDatesAsStrings to true .

$server = 'server\instance,port';
$cinfo = array(
    "ReturnDatesAsStrings"=>true,
    "Database"=>'database',
    "UID"=>"user",
    "PWD"=>"password"
);

Documentation about sqlsrv_connect() connection options can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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