Mysql PDO Connection and Create Mysql Table With PDO

Abhigyan Singh 12th Jul 2020

PDO(PHP Data Objects) is a PHP extension to PHP's database connections. As we all know that in PHP 5.5 MySQL is deprecated.  So we have to move new extensions (PDO) for database connection.

In this below tutorial, I’ll show you how to connect to MySQL database using PDO class.  Please follow bellows steps for connect a database using PDO. We just create bellows code for create database connection using PDO.

Step: 1

Firstly, we need to create a database for operation. I have created a new database name "myTestDatabase".

<?php
$host = 'localhost';
$dbname = 'myTestDatabase';
$username = 'root';
$password = '';

try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
$conn = null;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>

Fine, database connection is done. Now we’ll explain about above code details.

1. $host is your host name. I have use default host, “localhost”.

2. $dbname contain your database name. I have created database name “mytestDatabase”.

3. $username contains your database root username or master user name, which one you set on server installation time.

4. $password contains your database password or master password name, which one you set on server installation time.

If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block.

Final Code looks like below:

<?php

$host = 'localhost';
$dbname = 'myDB';
$username = 'root';
$password = '';

try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
$conn = null;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}

?>

Step: 2

I have created a table named 'my_test_table’.  You can use bellows code to create table.

CREATE TABLE IF NOT EXISTS ` my_test_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
`email_id` varchar(50) NOT NULL,
`contact_no` bigint(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

Finally table created is done. Now we need to insert data to created table. We’ll discuss about data insert, update & delete operation on next tutorial. If you face problem to connect database & create table using PDO, feel free to comment your suggestions regarding this tutorial without any hesitation.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

ALSO ON DISCUSS DESK