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:
mysql_fetch_assoc()
mysql_free_result()
mysql_fetch_row()
But I didn't succeed to display (get) the actual value.
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'];
If you only need the value:
$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);
$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];
Try this code.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With