SQL计数查询返回预设为1而不是实际行数的行数

时间:2017-06-16 20:15:45

标签: php mysql

下面是PHP代码,我从中获取数据库表中的多个行。但是下面的代码总是以1为单位返回多行。请帮我解决问题,从数据库中获取正确的行数。

$db=mysqli_connect("localhost","root","","test");               
     echo "<div class='row text-center col-lg-12' align='center'>";     
    $cmd="SELECT COUNT(*) FROM product WHERE product_name LIKE '%$search_query%'";

    $result = mysqli_query($db, $cmd);
    $total = mysqli_num_rows($result);

2 个答案:

答案 0 :(得分:2)

如果您执行SELECT COUNT(*),您将获得一行,其中计数值位于第一列。所以你需要获得COUNT()这样的值:

$result = mysqli_query($db, $cmd);
$row = mysqli_fetch_array($result);
$total = $row[0];

答案 1 :(得分:0)

这应该有效:

$db=mysqli_connect("localhost","root","","test");               
     echo "<div class='row text-center col-lg-12' align='center'>";     
    $cmd="SELECT * FROM product WHERE product_name LIKE '%$search_query%'";

    $result = mysqli_query($db, $cmd);
    $total = mysqli_num_rows($result);