You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP MySQL输出最后1条及最后4条数据库记录的方法求助

Hey there! Let's tackle your two PHP/MySQL questions one by one, and I'll help you adjust your existing script to meet those needs.


获取数据库的最后一条记录

First off, to get the "last" record, we need to define what "last" means—we usually rely on an auto-increment primary key (like an id field, assuming your formulier table has one) because databases don't natively track insertion order.

Modify your SQL query to sort records by the auto-increment ID in descending order, then only grab the first result:

$result = mysql_query("SELECT * FROM formulier ORDER BY id DESC LIMIT 1");
  • ORDER BY id DESC: Sorts records from newest (highest ID) to oldest
  • LIMIT 1: Only returns the top (newest) record

Since there's only one result, you can simplify the loop to a single fetch:

$row = mysql_fetch_array($result);
if ($row) {
    echo "<tr>";
    echo "<td>" . $row['tafel'] . "</td>"; // Replace with your actual field names
    echo "</tr>";
}

获取数据库的最后4条记录

For the last 4 records, we'll use a similar sorting approach. If you want the results to display in the original insertion order (oldest to newest among the last 4), we'll wrap the query in a subquery to reverse the sort:

Update your SQL to this:

$result = mysql_query("SELECT * FROM (SELECT * FROM formulier ORDER BY id DESC LIMIT 4) AS temp ORDER BY id ASC");
  • Inner query: Grabs the 4 newest records (sorted descending)
  • Outer query: Re-sorts those 4 records to display from oldest to newest, which is more intuitive for most users

You can keep your existing while loop here since we'll have 4 records to iterate through:

while($row = mysql_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['tafel'] . "</td>"; // Replace with your actual field names
    echo "</tr>";
}

Critical Note: Deprecated mysql_* Functions

Quick heads-up: The mysql_connect, mysql_query, and related functions you're using were removed in PHP 7.0 and marked as deprecated way back in PHP 5.5. They pose security risks and won't work on modern PHP versions.

Here's a safe, updated version of your script using mysqli (the recommended replacement) for fetching the last 4 records:

<?php
$con = mysqli_connect("localhost","test","test", "test"); // Directly specify the database name
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

// Query for the last 4 records, sorted in insertion order
$result = mysqli_query($con, "SELECT * FROM (SELECT * FROM formulier ORDER BY id DESC LIMIT 4) AS temp ORDER BY id ASC");

echo "<table border='1'> <tr> <th>tafel</th> </tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['tafel'] . "</td>";
    echo "</tr>";
}

mysqli_close($con);
?>

内容的提问来源于stack exchange,提问作者Jamezz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:29:49