Count The Number Of Rows In The Database Table Using PHP/MySQL

This tutorial will teach you on how to count the number of rows in your database table using PHP PDO query. to start with, follow the steps bellow.

Creating Our Database

First we are going to create our database which stores our data. To create a database: 1. Open phpmyadmin 2. Then create database and name it as "tutorial". 3. After creating a database name, click the SQL and paste the following code.
  1. CREATE TABLE IF NOT EXISTS `birthday` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `date` varchar(100) NOT NULL,
  4. `name` varchar(100) NOT NULL,
  5. `gender` varchar(100) NOT NULL,
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;

Creating our Database Connection

Next step is to create a database connection and save it as "connect.php". In this Step, we will write our connection script in PDO format.
  1. <?php
  2. /* Database config */
  3. $db_host = 'localhost';
  4. $db_user = 'root';
  5. $db_pass = '';
  6. $db_database = 'tutorial';
  7.  
  8. /* End config */
  9.  
  10. $db = new PDO('mysql:host='.$db_host.';dbname='.$db_database, $db_user, $db_pass);
  11. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  12.  
  13. ?>

Writing our script to get the number of rows

The code bellow will provide us the number of rows in our databse table.
  1. <?php
  2. include('connect.php');
  3. $sql = $db->prepare("SELECT count(*) FROM birthday");
  4. $sql->execute();
  5. $rows = $sql->fetch(PDO::FETCH_NUM);
  6. $numberofrows=$rows[0];
  7. echo 'Result : '.$numberofrows;
  8. ?>

Comments

Submitted byram_123 (not verified)on Thu, 03/13/2014 - 22:03

instead of this total code use mysqli_num_rows($result); command
Submitted byBuck (not verified)on Sat, 11/15/2014 - 08:48

In reply to by ram_123 (not verified)

What you wrote is not for PDO. Please re-read original post.

Add new comment