2015-08-08 43 views
1

我使用Microsoft ODBC 11驱动程序通过PHP连接到MSSQL数据库。我正在查询数据库,并收到我想要的数据,但显示时出现问题。我从数据库中获取的数组有一些对象是日期,我不知道如何在表中正确显示它们。现在我收到一个可捕获的致命错误:类DateTime的对象无法转换为字符串将对象转换为字符串MSSQL PHP

这里是代码。第二个foreach中的注释代码是我试图将该对象转换为字符串并仅显示没有该对象的其他属性的日期的地方。

<?php 
    header('Content-type: text/html; charset=utf-8'); 
    require_once('sqlcon.php'); 

    $sql = "SELECT * FROM dbo.operations WHERE OperType=4"; 
    $stmt = sqlsrv_query($conn, $sql); 
    if($stmt === false) { 
     die(print_r(sqlsrv_errors(), true)); 
    } 

    $tableHeaderWritten = false; 

    echo "<table>"; 
    while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { 
     if(!$tableHeaderWritten) { 
       echo "<tr>";   
       foreach ($row as $columns => $rows) { 
        //var_dump($row); 
       echo "<th>$columns</th>"; 
       } 
       echo "</tr>"; 
       $tableHeaderWritten = true; 
     } 

     echo "<tr>"; 
     foreach ($row as $columns => $rows) { 
       if(is_object($rows)) { 
        //$results = array(); 
        //$results = $rows->format('Y-m-d H:i:s'); 
        //foreach ($rows as $key => $value) { 
         //var_dump($value); 
         //echo "<th>$value</th>"; 
        } 

       } 

       echo "<th>$rows</th>"; 
       } 

     echo "</tr>"; 
    } 

    echo "</table>"; 

    ?> 

,这是甩数组我取:

`array (size=23) 
    'ID' => int 3756022 
    'OperType' => int 4 
    'Acct' => int 1 
    'GoodID' => int 3 
    'PartnerID' => int 1 
    'ObjectID' => int 4 
    'OperatorID' => int 1 
    'Qtty' => float 0 
    'Sign' => int 1 
    'PriceIn' => float 0 
    'PriceOut' => float 1.98 
    'VATIn' => float 0 
    'VATOut' => float 0 
    'Discount' => float 0 
    'CurrencyID' => int 1 
    'CurrencyRate' => float 1 
    'Date' => 
    object(DateTime)[1] 
     public 'date' => string '2015-05-25 00:00:00' (length=19) 
     public 'timezone_type' => int 3 
     public 'timezone' => string 'Europe/Paris' (length=12) 
    'Lot' => string ' ' (length=1) 
    'LotID' => int 1 
    'Note' => string 'Изтриване на период към 25.05.2015' (length=54) 
    'SrcDocID' => int 1 
    'UserID' => int 1 
    'UserRealTime' => 
    object(DateTime)[2] 
     public 'date' => string '2015-05-26 18:12:53' (length=19) 
     public 'timezone_type' => int 3 
     public 'timezone' => string 'Europe/Paris' (length=12)` 
+2

如果你的'

而(...)...'循环看起来像这样:[引擎收录:31892252 /转换对象到字符串MSSQL-PHP(http://pastebin.com/28y6U3gu)?未经测试。 –

+0

@RyanVincent非常感谢。这正是我需要的。你知道一个有用的资源,我可以阅读更多关于php中的对象。再一次感谢你 – intenZive

回答

1

感谢瑞安文森特我有一个解决我的问题。我只发布第二个foreach其中是变化。

foreach ($row as $columns => $rows) { 
       if($rows instanceof \DateTime) { 
        echo "<td>" , $rows->format('Y-m-d H:i:s') , "</td>"; 
       } 
       else 
       { 
        echo "<td>$rows</td>"; 
       }   
     }