[英]Format date output in 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 />";
}
?>
移动这一行:
$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注入的攻击。 您应该在实际使用脚本之前,通过将每个$_POST
引用包装在转义函数中来解决该问题,如下所示:
$name = mysql_real_escape_string($_POST["name"]);
看起来您没有显示错误,因为使用您的代码,您至少应该得到$ date的警告,该警告在首次使用时未定义。
这就像没有任何仪表盘的驾驶一样。
如果您在开发环境中工作,请确保显示错误(display_errors apache设置),并且您的错误级别很高(将error_reporting设置设置为-1以获得最大错误输出)。
您需要移动$date = date("l, F j, Y \\a\\tg:i:s \\P\\S\\T",$date);
进入while
循环
由于它位于循环之外,因此对于循环的每次迭代,数据库中的值都不会存储在$date
中。
您还需要将UNIX_TIMESTAMP(date)
更改为UNIX_TIMESTAMP(date) as date
查询中的UNIX_TIMESTAMP(date) as date
,以便将变量保存在结果行中,并带有您的代码期望的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.