我想让它先显示最新的帖子,然后再显示第二个,以此类推,我该如何处理这些事情?由于某种原因,它没有显示电子邮件地址…:(最后但同样重要的是:我如何添加像yyyy/mm/ddd hh:mm这样的时间戳?
<form method="post" onsubmit="#" action="gpost.php">
<fieldset>
Namn:<br><input name="gnamn" id="gnamn" type="text" size="20">
<br>E-post:<br><input name="gemail" id="gemail" type="text" size="20">
<br>Meddelande:<br>
<textarea name="gmeddelande" id="gmeddelande" cols="20" rows="10">
</textarea>
<br><br>
<input name="submit" type="submit" value="Sänd">
</fieldset>
</form>
<?php
$host="localhost";
$user="my user";
$pass="mypasswor :D";
$dbname="pelle";
$con=mysqli_connect($host,$user,$pass,$dbname);
if (mysqli_connect_errno($con))
{
echo "Misslyckades att ansluta till mysql: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT name,message FROM guestbook");
while($row = mysqli_fetch_array($result))
{ ?>
<div id="post">
<header><h3><?php echo $row['name']; ?></h3></header>
<p><?php echo $row['email']; ?></p>
<p><?php echo $row['message']; ?></p>
</div>
<?php }
mysqli_close($con);
?>
这是我的gpost.php
<?php
$host="localhost";
$user="my usernamen";
$pass="my password";
dbname="pelle";
$con=mysqli_connect($host,$user,$pass,$dbname);
if (mysqli_connect_errno($con))
{
echo "<h1>Failed to connect to MySQL: " . mysqli_connect_error() ."</h1>";
}
$name=$_POST['gnamn'];
$email=$_POST['gemail'];
$message=$_POST['gmeddelande'];
$sql="INSERT INTO guestbook(name,email,message) VALUES('$name','$email','$message')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
echo "Values Stored in our Database!";
mysqli_close($con);
?>
从Type INT向Database添加一个名为"time"的字段,值为"time()"php函数。
并从更改SQL
mysqli_query($con,"SELECT name,message FROM guestbook");
至
mysqli_query($con,"SELECT name,message,time FROM guestbook ORDER BY time DESC");
time():返回自Unix Epoch(1970年1月1日00:00:00 GMT)以来以秒为单位测量的当前时间。php.net 上的时间
date():字符串日期(string$format[,int$timestamp=time()])使用给定的整数时间戳或当前时间(如果未给定时间戳)返回根据给定格式字符串格式化的字符串。换句话说,时间戳是可选的,并且默认为时间()的值。php.net 上的日期
-
为了对数据进行排序,请在SQL查询中添加一个
ORDER BY
子句。例如:SELECT name,message,postedDate FROM guestbook ORDER BY postedDate DESC
您可以根据现有的任何数据进行订购,因此,如果您想根据记录发布的日期/时间进行订购,则需要在表中记录该信息。 -
它不会显示电子邮件,因为您没有选择电子邮件。用其他数据选择:
SELECT name,message,email FROM guestbook
-
您可以将任何您喜欢的列添加到表中。在MySQL中,您可能会使用
DATETIME
或TIMESTAMP
列类型。您可以像其他任何列一样插入到该列中,也可以像其他列一样从中进行选择。
要在创建新条目时将当前时间插入数据库,可以创建一个类型为"time"的字段,并将其设置为"TIMESTAMP",然后在PHP中为输出设置格式。电子邮件没有显示,因为您没有查询它。请将您的查询更改为:
"SELECT name, message, time, email FROM guestbook"
其中"电子邮件"是您的电子邮件字段的名称。或者,如果表中只有这些字段,您可以将其缩短为:
"SELECT * FROM guestbook"