以前在其他地方使用过它,但不记得如何。
而不是:
$cars = $mysqli->query("SELECT * FROM cars");
$count = $cars->num_rows();
if ($count) {
// is rows
}
我希望不必选择所有行或单个列,我只想要计数。
在我脑海里:
$cars = $mysqli->query("SELECT COUNT(*) as count FROM cars");
但是我如何使用该计数值呢?我需要在它上面运行一个if语句。
感谢。
答案 0 :(得分:4)
不建议在SQL中为名称使用保留字。所以我调用计数结果cnt代替。由于您的函数是标量,即您只希望返回一个值,因此可以使用:
$count = $mysqli->query("select count(*) as cnt from cars")->fetch_object()->cnt;
答案 1 :(得分:2)
如果结果是一个对象,那么:
$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'];
希望这有帮助。
答案 2 :(得分:1)
您有许多可用的选项。这是一个列表:
$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];
答案 3 :(得分:0)
选择查询始终返回结果集。
要计算,请使用fetch_row()
$result = $db->query("SELECT COUNT(*) FROM `cars`");
$cars= $result->fetch_row();
echo '#: ', $cars[0];// or use $c= $cars[0];
答案 4 :(得分:0)
您需要获得结果的第一行并查看'计数'列值:
$cars = $mysqli->query("SELECT COUNT(*) as count FROM cars");
$firstrow = $cars->fetch_assoc();
if ($firstrow['count'] > 0)
{
// ...
}