Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select count(*) from table of mysql in php

Tags:

php

mysql

count

I am able to get both the value and row of the mysql query result.

But I am struggling to get the single output of a query. e.g.:

$result = mysql_query("SELECT COUNT(*) FROM Students;");

I need the result to display. But I am not getting the result.

I have tried with the following methods:

  1. mysql_fetch_assoc()
  2. mysql_free_result()
  3. mysql_fetch_row()

But I didn't succeed to display (get) the actual value.

like image 534
Gana Avatar asked Aug 02 '11 05:08

Gana


4 Answers

You need to alias the aggregate using the as keyword in order to call it from mysql_fetch_assoc

$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];
like image 119
Shakti Singh Avatar answered Oct 20 '22 20:10

Shakti Singh


If you only need the value:

$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);
like image 40
bmaupin Avatar answered Oct 20 '22 20:10

bmaupin


$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];

Try this code.

like image 17
avetarman Avatar answered Oct 20 '22 18:10

avetarman


Please start using PDO.

mysql_* is deprecated as of PHP 5.5.0 and will be removed entirely in 7. Let's make it easier to upgrade and start using it now.

$dbh = new \PDO($dsn, $user, $password);
$sth = $dbh->prepare('SELECT count(*) as total from Students');
$sth->execute();
print_r($sth->fetchColumn());
like image 13
Lee Davis Avatar answered Oct 20 '22 20:10

Lee Davis