php - 如果我在表名后使用任何条件,表的最后一行不显示

标签 php html mysql

我想显示我表中的所有数据。

但是如果我在 $sql="SELECT * FROM $tbl_name 之后使用/添加 ORDER BY id DESC 或任何代码,那么最后一行 没有显示。

<?php

include "db.php";

$tbl_name="report"; // Table name 

$sql="SELECT * FROM $tbl_name ORDER BY id DESC";

$result=mysql_query($sql);
$count=mysql_num_rows($result);
$ro = mysql_fetch_array($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count>=1) {

    echo "<table border='1' align='center' cellpadding='10'>
    <tr>
    <th>Reporter</th>
    <th>Message</th>
    <th>Reporter Ip Address</th>
    <th>Action</th>
    </tr>";

    while($row = mysql_fetch_array($result)) {

        echo "<tr>";
        echo "<td>" . $row['from'] . "</td>";
        echo "<td>" . $row['msg'] . "</td>";
        echo "<td>" . $row['to'] . "</td>";
        echo "<td class='middle'>" . $row['ip'] . "</td>";
        echo "<td><a class=\"confirmation\" href=\"report_delete.php?id=" . $row['id'] . "\">Delete</a></td>";

        echo "</tr>";

    }
    echo "</table>";

}

else {
    print "<p align='center'>Nothing found.</p>";
}

?>

最佳答案

当然,当您使用 DESC 时,它会从最高 ID 开始。然后调用:

$ro = mysql_fetch_array($result); // this is the first row.

它获取第一行。

然后你的循环:while($row = mysql_fetch_array($result)) 从第二行开始。

所以只需删除这个 $ro = mysql_fetch_array($result); 不需要的获取行。

强制性说明:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

示例 PDO 用法:

<?php

$db = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

$query = $db->query('SELECT * FROM report ORDER BY id DESC');
$rows = $query->fetchAll(PDO::FETCH_ASSOC);

if(count($rows) > 0) {

    echo "
        <table border='1' align='center' cellpadding='10'>
        <tr>
            <th>Reporter</th>
            <th>Message</th>
            <th>Reporter Ip Address</th>
            <th>Action</th>
        </tr>
    ";

    foreach($rows as $row) {
        echo "<tr>";
            echo "<td>" . $row['from'] . "</td>";
            echo "<td>" . $row['msg'] . "</td>";
            echo "<td>" . $row['to'] . "</td>";
            echo "<td class='middle'>" . $row['ip'] . "</td>";
            echo "<td><a class=\"confirmation\" href=\"report_delete.php?id=" . $row['id'] . "\">Delete</a></td>";
        echo "</tr>";
    }

    echo '</table>';

} else {
    echo "<p align='center'>Nothing found.</p>";
}

?>

关于php - 如果我在表名后使用任何条件,表的最后一行不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27897500/

相关文章:

php - 获取所有记录json_encode

php - 在函数之间传递数据库连接

javascript - 平滑滚动解决方法

MySQL报错无法添加外键约束

php - 尝试了解 PHP 密码盐/加密

php - 根据从父表获得的两个案例连接两个表

php - 从 MySQL 查询构建多维 PHP 数组

css - 如何解决div定位问题

javascript - 展开 折叠 div

mysql - 如何计算百分比?