2015-08-08 64 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>"; 
       }   
     }