我不太擅长 PHP,但我知道一些其他类似的语言。
现在我要做的是获取表中有多少行。这是我的代码。
$result = mysql_query("SELECT COUNT(*) FROM list");
$num_rows = mysql_num_rows($result);
echo $num_rows;
现在这段代码返回 1,而实际上是 3。这是为什么呢?谢谢你的帮助。
试试这样:
$result = mysql_query("SELECT COUNT(*) FROM list");
$num_rows = mysql_fetch_object($result);
print_r($num_rows);
注意:不推荐使用 Mysql_* 函数。因此不推荐。
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT COUNT(*) as total_row FROM list");
echo "<table border='1'>
<tr>
<th>total_row</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['total_row'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
$result = mysql_query("SELECT COUNT(*) as total FROM list");
$num_rows = mysql_num_rows($result);
echo $num_rows; // output 1;
$rows = mysql_fetch_object($result);
echo $rows->total; // output 3;
你应该这样做:
$result = mysql_query("SELECT * FROM list");
$num_rows = mysql_num_rows($result);
echo $num_rows;
如果要通过 获取总行数COUNT
,可以这样做:
$result = mysql_query("select count(*) FROM list");
$row = mysql_fetch_array($result);
echo $row[0];
检查这个
$result = mysql_fetch_array(mysql_query("SELECT COUNT(*) as count FROM list"));
echo $result['count'];
它返回单列中的行数,然后只返回 1
参考: http ://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
只更改您的查询
$result = mysql_query("SELECT * FROM list");
$num_rows = mysql_num_rows($result);
echo $num_rows;
它返回一行,因为下面的查询只返回一个值,即行数。
$result = mysql_query("SELECT COUNT(*) FROM list");
我认为这应该有所帮助:
$result = mysql_query("SELECT COUNT(*) FROM list");
$num_rows = $result->fetchColumn();
echo $num_rows;