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.
CREATE TABLE IF NOT EXISTS `birthday` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`
date` varchar
(100) NOT
NULL,
`name` varchar(100) NOT NULL,
`gender` varchar(100) NOT NULL,
) 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.
<?php
/* Database config */
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'tutorial';
/* End config */
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_database, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Writing our script to get the number of rows
The code bellow will provide us the number of rows in our databse table.
<?php
include('connect.php');
$sql = $db->prepare("SELECT count(*) FROM birthday");
$sql->execute();
$rows = $sql->fetch(PDO::FETCH_NUM);
$numberofrows=$rows[0];
echo 'Result : '.$numberofrows;
?>