我有以下代码来显示表中记录的数字,即使我将列名更改为另一个列名,它也总是显示1;
然而,工作台中的相同查询显示正确的记录数。见截图;
$con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "classicmodels" ) or die ("Couldn't connect to server");
//get total number of records
$query = "SELECT count(checkNumber) FROM payments";
$result = mysqli_query ( $con, $query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
$rec_count = mysqli_num_rows($result);
echo $rec_count."<br>";
答案 0 :(得分:5)
这是因为num_rows
显示您获取的行数,在这种情况下,只有一行。您应该从数据库中获取count(checkNumber)
字段,其中包含行数,而不是num_rows
函数。
将它计为变量更好,例如COUNT(someField) as FieldCount
答案 1 :(得分:1)
结果中只会有一行。您应该获取记录然后回显$ record [&#39; count(checkNumber)&#39;]。 (别名会使索引更直观)。
答案 2 :(得分:1)
您在查询中使用count函数,它将在一行中给出答案。要使用获得正确的答案,您可以删除count()并保持其余代码相同。请参阅以下代码。
$con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "classicmodels" ) or die ("Couldn't connect to server");
//get total number of records
//I have Removed COUNT() from query
$query = "SELECT checkNumber FROM payments";
$result = mysqli_query ( $con, $query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
$rec_count = mysqli_num_rows($result);
echo $rec_count."<br>";
OR
您可以使用count()函数并获得正确的答案。
$con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "classicmodels" ) or die ("Couldn't connect to server");
//get total number of records
$query = "SELECT count(checkNumber) FROM payments";
$result = mysqli_query ( $con, $query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
while($rec_row = mysqli_fetch_row($result))
{
$rec_count=$rec_row['count(checkNumber)'];
}
echo $rec_count."<br>";