encrypted21 encrypted21 - 1 year ago 50
SQL Question

How to retrieve and display a COUNT query result in PHP?

I'm a beginner who has problems with PHP :(

I have a PHP function which shows all the rows from the database table. Now I have to create paging to show only limited number of rows per one page.

I have a problem with retrieving a COUNT result from query. I want to create a condition where PHP & MySQL use LIMIT if number of rows is bigger than needed on one page.

The following code:

$count = "SELECT COUNT(*) FROM articles";
$countq = $db->query($count);
$countrs = mysql_fetch_array($countq);
echo $countrs;

should display a number of rows. However, it does not. What am I doing wrong? I want to see a result to make sure that everything else will work fine. But I can't get it working.

Error: mysql_fetch_array() expects parameter 1 to be resource, object given

$db contains database connection information (server, user...) and is working


Use PDO for MySQL query.

$db = new PDO('mysql:host=#YOUR HOST#;dbname=#YOUR DB#;charset=utf8', '#YOUR LOGIN#', '#YOUR PASSWORD#');
$query = $db->query('SELECT COUNT(*) AS count FROM articles');
$countq = $query->fetch();
echo $countq['count'];

I hope this will help you