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 oldestLIMIT 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>"; }
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>"; }
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

