+-
SELECT COUNT(*)AS计数-如何使用此计数

代替执行:

$cars = $mysqli->query("SELECT * FROM cars");
$count = $cars->num_rows();
if ($count) {
  // is rows
}

我不想只选择所有行或一列,我只想要计数。

在我的头上:

$cars = $mysqli->query("SELECT COUNT(*) as count FROM cars");

但是我该如何使用该计数值?我需要对其运行if语句。

5
投票

不建议对SQL中的名称使用保留字。因此,我将计数结果称为cnt。由于您的函数是标量,即您只希望返回一个值,因此可以使用:

$count = $mysqli->query("select count(*) as cnt from cars")->fetch_object()->cnt; 
1
投票

选择查询始终返回结果集。要计算计数,请使用fetch_row()

$result = $db->query("SELECT COUNT(*) FROM `cars`");
$cars= $result->fetch_row();
echo '#: ', $cars[0];// or use $c= $cars[0];
1
投票

如果结果是对象,则:

$cars = $mysqli->query("SELECT count(*) as count FROM cars");
$carRows = $cars->result();
echo $carRows[0]->count;

如果返回数组,则:

$cars = $mysqli->query("SELECT count(*) as count FROM cars");
$carRows = $cars->result_array();
echo $carRows[0]['count'];

希望这会有所帮助。

1
投票

您需要获得结果的第一行并查看“计数”列的值:

$cars = $mysqli->query("SELECT COUNT(*) as count FROM cars");
$firstrow = $cars->fetch_assoc();

if ($firstrow['count'] > 0)
{
  // ...
}
0
投票

您有很多选择。这是一个列表:

使用关联数组:
$count = $mysqli->query("SELECT COUNT(*) as count FROM cars")->fetch_array()['count'];
使用数值数组:
$count = $mysqli->query("SELECT COUNT(*) FROM cars")->fetch_array()[0];
使用对象符号
$count = $mysqli->query("SELECT COUNT(*) as count FROM cars")->fetch_object()->count;

重要点。如果需要在查询中使用变量输入,则应使用预处理语句。为了得到计数,它看起来像这样:

$stmt = $mysqli->prepare("SELECT COUNT(*) FROM cars WHERE category=?");
$stmt->bind_param('s', $category);
$stmt->execute();
$count = $stmt->get_result()->fetch_row()[0];