Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP echo SQL Count [duplicate]

Tags:

sql

php

mysql

Okay, so I am having a problem. I seem to be unable to successfully echo an SQL Count in PHP.

SQL:

SELECT TableA.C, COUNT(*) FROM TableA JOIN TableB ON (TableA.C = TableB.D) 
   WHERE TableB.E = 1 GROUP BY TableA.C ORDER BY COUNT(*) DESC

PHP:

$result= mysql_query("SELECT TableA.C, COUNT(*) FROM TableA JOIN TableB ON (TableA.C = TableB.D) 
   WHERE TableB.E = 1 GROUP BY TableA.C ORDER BY COUNT(*) DESC");

while($rows = mysql_fetch_array($result))
{
     echo $rows['Count']."</br>";
}
$rows = mysql_fetch_array($result);
{
     echo $rows['Count'];
}

I've tried two different things I've found online (the above). I even tried one with "mysql_fetch_array($result, MYSQL_ASSOC)" instead of just mysql_fetch_array($result).

Each time, I get the same error messages:

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in 

/home/semsemx1/public_html/x/xx.php

Additionally, I've tried capitalizing as "$rows['COUNT']", but that doesn't work.

Any help would be appreciated.

like image 876
Witold Kowelski Avatar asked Feb 14 '26 06:02

Witold Kowelski


2 Answers

You just need to give your count an ALIAS

SELECT TableA.C, COUNT(*) as total

then you can call it with

echo $rows['total']

Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO

like image 171
Fabio Avatar answered Feb 15 '26 20:02

Fabio


Use "As" keyword

SELECT TableA.C, COUNT(*) as count FROM TableA JOIN TableB ON (TableA.C = TableB.D) WHERE TableB.E = 1 GROUP BY TableA.C ORDER BY COUNT(*) DESC


 echo $rows['count '];
like image 23
Igor S. Avatar answered Feb 15 '26 19:02

Igor S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!