我想显示我表中的所有数据。
但是如果我在$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);
不需要的获取行。
必填说明:
请不要在新代码中使用
mysql_*
函数。它们不再维护并被正式弃用。看到红框了吗?请改为了解预准备语句,并使用 PDO 或 MySQLi - 本文将帮助您决定哪个语句。如果您选择PDO,这是一个很好的教程。
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>";
}
?>
在循环之前,您有一个额外的mysql_fetch_array($result);
。
必须正确生成 Sql 查询字符串。喜欢这个:
$sql = "SELECT * FROM ".$tbl_name." ORDER BY id DESC";
在 Php 中有两个字符串运算符。第一个是串联运算符 ('.'),它返回其左右参数的串联。第二个是连接赋值运算符 ('.='),它将右侧的参数附加到左侧的参数。
更多信息 -> http://php.net/manual/en/language.operators.string.php
希望对您有所帮助。