Getting Row Count

You can get a PDOStatement and do rowCount(). PDO offers a function for returning the number of rows found by the query, PDOstatement::rowCount(). But you will hardly need it, as there are much easier options like using count() php function to count array returned by query. We will learn below. PDO has PDOStatement::rowCount(), which apparently does not work in MySql

Example : (Wrong Way of Counting Row)

<?php

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

$stmt = $db->query('SELECT * FROM table');

$row_count = $stmt->rowCount();

echo $row_count.' rows selected';

But, This is terrible thing to use, You should never use rowCount() , for just counting the number of rows returned.

Right Way :-

one have to ask a database to count them, and return the result in a single row:

<?php

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

$count = $db->query("SELECT count(1) FROM table")->fetchColumn();

echo $count;

$nRows = $pdo->query('select count(*) from table')->fetchColumn(); 

echo $nRows;

?>
  • To count number of rows in the table, use SELECT COUNT(*) query as they are more efficient.
  • To count no. of rows returned by query, use rowCount() or simply call count() php function on the array returned by fetchAll()

Some of the content has been taken from php.net and wikipedia.com website.


Loading ...

Related Results :

  1. Getting Row Count
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author