2013-04-07 49 views
-2

我一直在學習使用PDO與PHP的基礎知識,我的查詢工作。 這是代碼:Strtotime和PHP - 格式化PDO查詢?

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', '1'); 
?> 



<?php 
$hostname = "localhost"; 
$username = "test"; 
$password = "test"; 

try { 
    $db = new PDO("mysql:host=$hostname;dbname=goodsdb", $username, $password); 

    //echo "Connected to database"; // check for connection 

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); 

    $sql = "Select * from items"; 
    $result = $db->query($sql); 
    foreach ($result as $row) { 
     //echo $row["goods"]. "<br />"; 
    } 

    $db = null; // close the database connection 

} 
catch(PDOException $e) { 
    echo $e->getMessage(); 
} 
?> 
<p> 
<?php 
echo $row["goods"]; 
?> 
</p> 
<p> 
<?php 
echo $row["auctiondate"]; 
?> 
</p> 
</div> 
<?php require 'footer.php' ?> 

它的工作,到目前爲止沒有任何錯誤。請注意,我在foreach之後註釋了echo部分,並使用php分隔符回顯了行 - 這是一種好的做法,還是應該取消註釋?

不過,我如何獲得我的數據庫中auctiondate字段中顯示的數據爲:

2013年4月6日,下午12:00

而不是

2013年6月6日12:00 :00(它作爲DATETIME存儲在數據庫中)

我不確定是否使用date或strtotime來顯示此內容,並希望幫助獲取日期以正確格式化。

該項目是一個簡單的網站,用於顯示PDO/MySQL中倉庫的數據庫數據 - 基本上是一個簡單的測試站點。

我使用PHP 5.4.4,並且在OS X 10.8.3 Mountain Lion上使用MAMP,如果這有幫助的話。

+0

請接受你選擇的答案! – michi 2013-04-08 15:11:10

回答

3

無論是在PHP中使用的日期格式的功能或使用mysql DATE_FORMAT功能是這樣的:

Select *,date_format(auctiondate,'%D %M %Y, %h:%i%p') as 'mod_date' from items 

這將在現場恰好返回6th April 2013, 12:00pmmod_date

1

由於你的問題出於某些原因用PDO標記(與日期無關墊),我會做的方式進行一些改進您使用PDO

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', '1'); 

$hostname = "localhost"; 
$username = "test"; 
$password = "test"; 

$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); 
$db = new PDO("mysql:host=$hostname;dbname=goodsdb", $username, $password, $opt); 

$sql = "Select * from items"; 
$result = $db->query($sql); 
foreach ($result as $row) { 
    //echo $row["goods"]. "<br />"; 
} 

這將是處理PDO錯誤的正確方法