2014-09-11 44 views
-2

所以我有日期時間演示文稿的問題。 我想在列表中標題旁邊的條目中顯示條目的時間。 但目前,只要我嘗試正確格式化時間,代碼只顯示一個條目而不是全部。 任何人都可以幫助我嗎?Dislpay正確的日期時間從數據庫在PHP

<?php 
    $result = mysql_query("SELECT * FROM posts"); 

    while ($row = mysql_fetch_array($result)){ 
     echo "<li>{$row["date"]}". "&nbsp; &nbsp; &nbsp; &nbsp;". $row["title"]. "</li>"; 
    } 
?> 

這樣它顯然只是表明什麼在db:

2014-09-08 07:09:24.476246  this is it !! 
2014-09-05 06:20:20.317560  So nun endlich die Website online 

但是當我莫名其妙格式中的日期是這樣的...

<?php 
    $result = mysql_query("SELECT * FROM posts"); 

    $new_date = mysql_fetch_row($result); 
    $date = date_create($new_date[3]); 

    while ($row = mysql_fetch_array($result)){ 
     echo "<li>". date_format($date, 'Y-m-d H:i:s'). "&nbsp; &nbsp; &nbsp; &nbsp;". $row["title"]. "</li>"; 
    } 
?> 

我只得到了最後一排從數據庫。

+0

不是你的問題的答案,但檢查出http://php.net/manual/en/function.mysql-query.php。你看到那個大紅色的盒子?如果你正在編寫新的PHP代碼,你應該注意它所說的。總之,使用'mysqli_'或'PDO'函數代替。 – 2014-09-11 13:18:07

回答

0

嘗試與date()格式化直接在環所以無需$date VAR

echo "<li>".date('Y-m-d H:i:s', strtotime($row["date"]))."&nbsp; &nbsp; &nbsp; &nbsp;". $row["title"]. "</li>"; 

或只是讓你的

$date = date_create($new_date[3]); 

循環

而且mysql_*已經被廢棄了更多的內按照@約翰孔德的答案。

0

通過在循環之外調用mysql_fetch_row(),您將記錄集的第一條記錄從堆棧中彈出,僅留下第二條記錄。只需在你的循環中創建你的DateTime()對象。

<?php 
    $result = mysql_query("SELECT * FROM posts"); 

    while ($row = mysql_fetch_array($result)){ 
     $date = date_create($row[3]); 
     echo "<li>". date_format($date, 'Y-m-d H:i:s'). "&nbsp; &nbsp; &nbsp; &nbsp;". $row["title"]. "</li>"; 
    } 
?> 

我也做不建議訪問相同數據時混合數值和關聯的密鑰。堅持一個。我推薦關聯數組,因爲它們對讀者來說更清楚。

<?php 
    $result = mysql_query("SELECT * FROM posts"); 

    while ($row = mysql_fetch_assoc($result)){ 
     $date = date_create($row['date_col']); 
     echo "<li>". date_format($date, 'Y-m-d H:i:s'). "&nbsp; &nbsp; &nbsp; &nbsp;". $row["title"]. "</li>"; 
    } 
?> 

Please, don't use mysql_* functions in new code。他們不再維護and are officially deprecated。查看red box?請改爲了解prepared statements,並使用PDOMySQLi - this article將幫助您決定哪個。如果您選擇PDO,here is a good tutorial

相關問題