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

时间:2015-01-12 07:57:22

标签: php html mysql

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

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

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

?>

3 个答案:

答案 0 :(得分:4)

当然,当您使用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。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择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>";
}

?>

答案 1 :(得分:0)

在循环之前你有一个额外的mysql_fetch_array($result);

答案 2 :(得分:0)

您必须正确地生成Sql查询字符串。像这样:

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

在Php中有两个字符串运算符。第一个是连接运算符('。'),它返回其左右参数的串联。第二个是连接赋值运算符('。='),它将右侧的参数追加到左侧的参数。

更多信息 - &gt; http://php.net/manual/en/language.operators.string.php

希望它有所帮助。