简体   繁体   English

如何制作一个仅显示MySQL最后20个值的php动态表?

[英]How to make a php dynamic table showing only the last 20 values from MySQL?

I have made a php table that displays data from MySQL table. 我做了一个PHP表,显示MySQL表中的数据。 This is working perfectly. 这很正常。 However, the MySQL table keeps getting updated and so my php table gets really long and big. 但是,MySQL表不断更新,因此我的php表又长又大。 I just want to keep it short, so I just want it to display the last 20 items on the table if possible. 我只想使其简短,所以我只希望它尽可能显示表格中的最后20个项目。

Also the table doesn't update dynamically, to see the new updates you have to keep refreshing the page and I would like it if it could keep updating on its own . 此外,该表格不会动态更新,要查看新更新,您必须不断刷新页面, 如果它可以自行更新我希望它能够更新 Here is the page of how the (long) table looks. 是(长)表外观的页面。

Here is my php code as of now: 这是到目前为止我的php代码:

<?php
    $con = mysql_connect("$host","$username","$pass"); 
    if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("$db_name", $con); //database name
    $result = mysql_query("SELECT * FROM $db_table"); //table

    echo "<table cellpadding='0' cellspacing='0' class='ver-minimalist'>
    <tr>
    <th>Photoresistor</th>
    <th>Accelerometer</th>
    </tr>";

    while($row = mysql_fetch_array($result))
    {
    echo "<tr>";
    echo "<td>" . $row['Photoresistor'] . "</td>";
    echo "<td>" . $row['Accelerometer'] . "</td>";
    echo "</tr>";
    }
    echo "</table>";

    mysql_close($con);
    ?>

I know I'm going to have to make a loop but I'm not sure which one would be the best option. 我知道我将不得不做一个循环,但是我不确定哪个将是最佳选择。 Please, I would really appreciate the help. 拜托,我将非常感谢您的帮助。

The MySQL table does have an ID -primary key if that helps. 如果有帮助,MySQL表确实具有ID-主键。

Make your query this: 进行以下查询:

SELECT * FROM $db_table ORDER BY id DESC LIMIT 20

Limit allows you to limit the amount of results you get from a query. 限制允许您限制从查询中获得的结果数量。 By sorting by ID you can get the last 20 results in your table. 通过按ID排序,您可以获得表中的最后20个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM