如何显示数据库中的最后五行

时间:2019-07-07 19:31:33

标签: php html mysql

我想编写HTML代码,显示数据库的最后五行,

我有显示最后一行的代码,但我想显示最后五行。

我的代码:

<?php
$conn = mysqli_connect("localhost", "root", "", "refd-2");
$sql = mysqli_query($conn, "SELECT * FROM last ORDER BY no DESC LIMIT 1");
$print_data = mysqli_fetch_row($sql);

echo $print_data[1];
echo "\n";

3 个答案:

答案 0 :(得分:1)

如果指定LIMIT 5,则可以从数据库中获取最后5个结果。

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli("localhost","root","","refd-2");
$con->set_charset('utf8mb4');

$result = $con->query("SELECT * FROM last ORDER BY no DESC LIMIT 5");

// Get all rows at once as an array of rows
$rows = $result->fetchAll();
print_r($rows);
// or use foreach loop
foreach($rows as $row) {
    print_r($row);
}

如果不需要,可以跳过fetchAll()方法,您可以直接在结果上循环。

foreach($result as $row) {
    print_r($row);
}

答案 1 :(得分:0)

将LIMIT 1更改为LIMIT 5,然后获取结果集。

 <?php
//database connectivity
$con=mysqli_connect("localhost","root","","refd-2") or die(mysqli_error());
//select  values from empInfo table
$sql = "SELECT * FROM last ORDER BY no DESC LIMIT 5'";
$result = mysqli_query($con,$sql);
print_r(mysqli_fetch_array($result));
mysqli_close($con);
?>

答案 2 :(得分:0)

尝试:

<?php
$conn = mysqli_connect("localhost", "root", "", "refd-2");
$sql = mysqli_query($conn, "SELECT * FROM last ORDER BY no DESC LIMIT 5");
while($print_data = mysqli_fetch_array($sql)){

echo $print_data["row"]; 
// here you will change the name "row" to your database row name
echo "\n";
}
?>