peat wedty
peat wedty

Reputation: 55

How to count mysql with using group by PHP?

How to count mysql with using group by PHP ?

When i test this code it's echo 1

How to do for echo 3 (by count country)?

This is my table_test

_____________________
|__id___|__country__|
|__1____|____usa____|
|__2____|____usa____|
|__3____|___china___|
|__4____|____uk_____|

This is my code.

<?PHP
$result = mysql_query("SELECT COUNT(*) FROM table_test GROUP BY country");
$row = mysql_fetch_row($result);
mysql_free_result($result);
$all_country = $row[0];
echo $all_country;
?>

Upvotes: 1

Views: 154

Answers (3)

Sanjiv Dhakal
Sanjiv Dhakal

Reputation: 316

Try:

SELECT Country,COUNT(*) FROM table_test GROUP BY country

Upvotes: 3

sunilwananje
sunilwananje

Reputation: 724

use this code for counting rows of selected query

 <?php
$result = mysql_query("SELECT COUNT(*) FROM table_test GROUP BY country");
$row = mysql_fetch_row($result);
$all_country = mysql_num_rows($result);
echo $all_country;
?>

Upvotes: 0

Dhara Parmar
Dhara Parmar

Reputation: 8101

1) Use mysqli_* API instead of mysql_* API

2) Use mysqli_num_rows to get total row returned

$sql="SELECT COUNT(*) FROM table_test GROUP BY country";

 if ($result=mysqli_query($con,$sql))
 {
    $rowcount=mysqli_num_rows($result);
 }

echo $rowcount; // print 3

Upvotes: 0

Related Questions