我的数据库中有一个名为quote的表,有5行。但是,当我尝试计算行时,它总是返回1而不是5.我使用下面的代码:
$connection = mysqli_connect("host","username","password","database");
$querya = "SELECT COUNT(id) FROM quote";
$resulta = mysqli_query($connection, $querya);
$max = mysqli_num_rows($resulta);
$srow = rand(1,$max);
<br /> There are <?php echo $max ?> number of rows
我正在计算作为主键的id列,因此永远不会为空。我也尝试使用count(*)但得到相同的结果。我哪里错了?
答案 0 :(得分:5)
您无法将mysqli_num_rows
与count
配对。如果您想使用mysqli_num_rows
,则必须select *
(这会很慢)。而是select count(*) as total
,并使用total
。
答案 1 :(得分:1)
如果您想在查询中使用COUNT()
,请为其指定一个可以返回的别名:
$querya = "SELECT COUNT(`id`) AS `Total` FROM `quote`";
$resulta = mysqli_query($connection, $querya);
$row = mysqli_fetch_assoc($resulta);
echo $row['Total']; // identifier here is the same as the alias in the query