SELECT COUNT(*) AS count - How to use this count

半腔热情 提交于 2020-05-22 07:50:51

问题


Instead of doing:

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

I want to not have to select all rows or a single column, I simply want the count.

In my head:

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

But then how do I use that count value? I need to run an if statement on it.


回答1:


It's not recommended to use reserved words for names in SQL. So I call the count result cnt instead. As your function is scalar, i.e. you expect only one value back, you can use:

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



回答2:


Select queries always return a resultset. To take the count, use fetch_row()

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



回答3:


You need to get first row of your result and see the 'count' column value:

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

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



回答4:


If result is an object then:

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

If you return array then:

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



回答5:


You have many options available. Here is a list:

  • Using associative array:
$count = $mysqli->query("SELECT COUNT(*) as count FROM cars")->fetch_array()['count'];
  • Using numerical array:
$count = $mysqli->query("SELECT COUNT(*) FROM cars")->fetch_array()[0];
  • Using an object notation
$count = $mysqli->query("SELECT COUNT(*) as count FROM cars")->fetch_object()->count;

Important point. If you need to use variable input in your query then you should use prepared statement. To get the count then it would look like this:

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


来源:https://stackoverflow.com/questions/28561154/select-count-as-count-how-to-use-this-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!