2010-11-12 191 views
0

我是PHP新手,不認爲自己是編碼人員。我正在處理我的第一個數據庫驅動操作,並且無法正確地格式化日期輸出。我正在格式化日期的行似乎被忽略。我做了一件令人難以置信的錯誤?格式日期輸出PHP

這是在頁面上輸出:

Comment from: Jeremiah 
1289594028 

here is my comment 

下面是代碼:

<?php 

    $name = $_POST['name']; 
    $comment = $_POST['comment']; 


    if($name && $comment and ereg("^[A-Za-z0-9' -]+$",$name) and ereg("^[A-Za-z0-9' -,.:;()!?&#@'/]+$",$comment)) 

    { 
     mysql_query("insert into pilot_comments (name,comment,date,page) values ('$name', '$comment',NOW(),'challenge1')"); 
    } 

    elseif($_POST['submitted']==1) 

    { 
     echo "<img src='images/structure/commenting_spacer.png' height='1' width='249'>"; 

     echo "<br /><br /><div style='width:209px; background-color:#ff0000; padding:20px'><span class='white bold fourteen'>Uh oh! You may have:<br /><br />(1) Entered special characters, or <br /><br />(2) Not entered text into both fields.</span><br /><br /><span class='white twelve'>(This helps me fight spam. Thanks for understanding.)</span></div><br /><br />"; 
    } 

?> 

<?php 

    $result = mysql_query("select name,comment,UNIX_TIMESTAMP(date) from pilot_comments where page='challenge1' order by date desc"); 

    echo mysql_error(); 

    $date = date("l, F j, Y \a\t g:i:s \P\S\T",$date); 

    while(list($name,$comment,$date) = mysql_fetch_row($result)) 

    { 
     echo "<img src='images/structure/commenting_spacer.png' height='1' width='249'>"; 

     echo "<div STYLE='word-wrap:break-word;width:249px;left:0px'><span class='twelve gray'><br />Comment from: </span><span class='twelve gray bold'>$name</span></div>"; 

     echo "<span class='ten light-gray bold'>$date<br /><br /></span>"; 

     echo "<div STYLE='word-wrap:break-word;width:249px;left:0px'><span class='fourteen green bold'>$comment</span></div><br /><br />"; 
    } 
?> 

回答

3

移動這一行:

$date = date("l, F j, Y \a\t g:i:s \P\S\T",$date); 

while循環中(其中新$date是在每次迭代中創建的,因此您的格式將丟失):

while(list($name,$comment,$date) = mysql_fetch_row($result)) 

    { 

    $date = date("l, F j, Y \a\t g:i:s \P\S\T",$date); 

    ... rest goes here ... 

順便說一下,您的代碼容易受到SQL injection的影響。您應該修復,使用在現實世界中使用腳本之前通過包裹的$_POST每提一個逃生功能,像這樣:

$name = mysql_real_escape_string($_POST["name"]); 
+0

+1用於指出此漏洞。 – 2010-11-12 20:48:39

+0

當然,MySQL完全有能力完成日期格式化:http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format。可能會更好地做到DB端,並保存雙重轉換(mysql日期 - >字符串,而不是mysql - > php - >字符串)。 – 2010-11-12 21:12:21

+0

謝謝。沒有問題的作品。另外感謝您收緊我的安全! – Jeremiah 2010-11-12 23:25:52

0

它看起來像你不顯示錯誤,因爲你的代碼,你應該至少獲取$ date的警告,這在第一次使用時是未定義的。

這就像駕駛沒有任何儀表板。

如果您正在開發環境中,請確保顯示錯誤(display_errors apache設置),並且錯誤級別較高(將error_reporting設置設置爲-1以獲得最大錯誤輸出)。

0

你需要移動$date = date("l, F j, Y \a\t g:i:s \P\S\T",$date);while

有了它的循環之外,從數據庫中值是沒有得到存儲在$date爲循環的每個迭代。

您還需要在查詢中將UNIX_TIMESTAMP(date)更改爲UNIX_TIMESTAMP(date) as date,以便變量以您的代碼所期望的名稱保存在結果行中。