仅回显插入到 MYSQL 数据库中的最后 4 件事


only echoing the last 4 things inserted into a MYSQL database

我得到了这个脚本,它回显了来自 MySQL 数据库的信息。
现在一切正常,但我只想回显插入的最后 4 条语句

这是脚本

               <?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("blog") or die(mysql_error());
$result = mysql_query("SELECT * FROM blog") 
or die(mysql_error());  
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
while($row = mysql_fetch_array( $result )) {
    echo "<tr><td>"; 
    echo $row['id'];
    echo "</td><td>"; 
    echo $row['username'];
    echo "</td></tr>"; 
} 
echo "</table>";
?> 

修改你的 mysql 查询(我假设每个条目都是升序 id(:

SELECT * FROM blog
ORDER BY id DESC
LIMIT 4;

但这会使它们以相反的顺序排列。如果您希望它们按正确的顺序排列,您可以执行以下操作:

SELECT * 
FROM (
    SELECT * FROM blog
    ORDER BY id DESC
    LIMIT 4
) last_four
ORDER BY id ASC;

如果您有一个自动递增的列作为每篇博客文章的 id,您可以按降序对 id 进行排序。使用如下查询

mysql_query("SELECT * FROM blog ORDER BY your_id_column DESC LIMIT 4") 

假设您的blog表有一个名为 created 的列,其中包含帖子的创建日期,则此查询应执行您需要的操作:

SELECT * FROM blog ORDER BY created DESC LIMIT 4

这将按最近创建的帖子(按时间顺序(对您的帖子进行排序,并且只会返回从表中获取的前 4 行。

您将对查询执行此操作,将查询更改为如下所示的内容:

select * from blog order by blog_id desc limit 4

您必须将blog_id更改为您使用的任何内容。

使用此查询,它将按 ID 降序对记录进行排序,并使用 limit 仅获取最后 4 条记录。

SELECT * FROM blog order by ID DESC LIMIT 4

您可以使用 LIMIT 和 ORDER BY 来限制您的 SELECT,但为了提供帮助,我们需要更多地了解数据库结构。 你能提供"描述博客"的结果吗?

如果您的"id"字段设置了auto_increment,那么该字段的数字越多表示最近的帖子越好。 以相反的顺序显示输出("ORDER BY id DESC"(和限制数量("LIMIT 4"(应该相当简单。

  SELECT * FROM blog ORDER BY id DESC LIMIT 4;

在MySQL文档中查看SELECT命令的精确结构。

<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("blog") or die(mysql_error());
$result = mysql_query("SELECT * FROM `blog` ORDER BY `id` DESC LIMIT 4") or die(mysql_error());  
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
while($row = mysql_fetch_array( $result )) {
    echo "<tr><td>"; 
    echo $row['id'];
    echo "</td><td>"; 
    echo $row['username'];
    echo "</td></tr>"; 
} 
echo "</table>";
?> 

只需复制并粘贴代码即可。我相信代码会很好用。谢谢