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

nom7f22z  于 2023-09-29  发布在  PHP
关注(0)|答案(5)|浏览(141)

而不是做:

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

我不想选择所有行或单个列,我只想计数。
在我的脑海里:

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

那么,如何使用该计数值呢?如何在PHP中获取COUNT(*)的结果?

f4t66c6m

f4t66c6m1#

不建议在SQL中对名称使用保留字。所以我将计数结果称为cnt。因为你的函数是标量的,即如果你只期望返回一个值,你可以用途:

$count = $mysqli->query("select count(*) as cnt from cars")->fetch_object()->cnt;
7z5jn7bk

7z5jn7bk2#

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

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

2cmtqfgy3#

您需要获取结果的第一行,并查看'count'列的值:

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

if ($firstrow['count'] > 0)
{
  // ...
}
92dk7w1h

92dk7w1h4#

如果result是一个对象,则:

$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'];
6gpjuf90

6gpjuf905#

您有许多选项可用于从SQL获取计数。
如果你已经在使用PHP 8.1,最简单的方法是:

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

以下是其他可能的方法列表:

  • 使用关联数组:
$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];

相关问题