Tom Gillespie
Tom Gillespie

Reputation: 129

How can I echo a COUNT query

I'm new to mySQL and as such am just looking for a very simple COUNT query which I haven't found explained online with any real clarity.

What I'm looking to do is

COUNT the number of rows in my PASSENGER table where groupID = 0, and then be able to echo the numerical value that the count will return, how can I do this?

Upvotes: 0

Views: 22247

Answers (5)

Starx
Starx

Reputation: 78971

Something like this

$query = "SELECT COUNT(*) c FROM PASSENGER WHERE groupID = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
echo $row['c']; //Here is your count

Upvotes: 8

Lee Davis
Lee Davis

Reputation: 4756

$query = "SELECT COUNT(*) as result FROM passenger WHERE groupID = 0";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo "Number is: ", $row;

Upvotes: 2

Esben Tind
Esben Tind

Reputation: 885

The other answers sums this up pretty neat. Just want to add, in case you actually need the data from your passenger table later on in your script, it would be prudent not to make two seperate calls to get the count and the data. The best way to do this would be:

<?php
$query = "SELECT * FROM PASSENGER WHERE groupID=0";
$result = mysql_query($query);
$result_count = mysql_num_rows($result);
?>

As opposed to: SELECT PASSENGER.*, COUNT(*) as passenger_count FROM PASSENGER WHERE groupID=0

Upvotes: 0

Brendan
Brendan

Reputation: 3493

SELECT COUNT(*) FROM PASSENGER WHERE GROUPID = 0;

Upvotes: 0

Etienne Dupuis
Etienne Dupuis

Reputation: 13786

//get result
$data = mysql_query("SELECT count(*) as total FROM PASSENGER WHERE groupID = 0");
$info = mysql_fetch_assoc($data);

//output result
echo "Rows found :" . $info["total"];

Upvotes: 2

Related Questions