我的SQL总是返回1

时间:2015-12-01 14:52:38

标签: php mysql

我有这个查询。但是,它无法正常工作。 echo总是返回1,但db

中有3行
<?php
include "db_connect.inc.php";

$sql = "SELECT COUNT(id) FROM profiles";

$res = mysqli_query($con, $sql);

$num = mysqli_num_rows($res);
if ($num == 0) 
    echo "0";

echo $num;

mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:3)

您正在进行聚合查询,这意味着您将始终获得一行结果 - 一行包含您请求的count()值。即使count()为0,您仍然会获得一行结果。

如果要检查计数的值,则必须获取该行并检查字段的值,例如

$sql = "SELECT COUNT(id) AS cnt FROM profiles";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$row = mysqli_fetch_assoc($result);
if ($row['cnt'] == 0) { die("No profiles"); }

答案 1 :(得分:2)

您的查询返回值 3

1

要了解您的期望,您需要以下内容:

<?php
    include "db_connect.inc.php";
    $sql = "SELECT COUNT(id) myCount FROM profiles";
    $res = mysqli_query($con, $sql);
    if ($row = mysqli_fetch_array($res, MYSQLI_ASSOC) ) {
      echo $row['myCount'];
    } else {
      echo "0";
    }
    mysqli_close($con);
?>