This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

CRUD operation with PDO Database Connection

Updated on December 8, 2021

4 Min Read
PDO

Databases are everywhere and there is no practical PHP application that could exist without a database. From the very beginning, PHP offers several ways of interfacing with all popular DBMS. For instance, two popular ways of interfacing with MySQL based databases are mysql and mysqli.

Over years, databases have come a long way and now several different vendors offer popular DBMS that power modern PHP apps. To standardize and streamline development practices, PHP introduced PHP Data Objects (PDO) in PHP 5.1. These objects are used to setup PDO database connections.

PDO is a database access layer which provides a fast and consistent interface for accessing and managing databases in PHP applications.  Every DBMS has specific PDO driver(s) that must be installed when you are using PDO in PHP applications.

Supported Databases

Driver nameSupported Database

PDO_CUBRID Cubrid
PDO_DBLIB FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD Firebird
PDO_IBM IBM DB2
PDO_INFORMIX IBM Informix Dynamic Server
PDO_MYSQL MySQL 3.x/4.x/5.x
PDO_OCI Oracle Call Interface
PDO_ODBC ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL PostgreSQL
PDO_SQLITE SQLite 3 and SQLite 2
PDO_SQLSRV Microsoft SQL Server / SQL Azure
PDO_4D 4D

 

By default, PHP has PDO_SQLite driver installed. However, if you wish to work with other databases, you must first install the relevant driver.

in order to check what drivers are installed on your system, create a new PHP file and add the following code snippet to it:

<?php

print_r(PDO::getAvailableDrivers());

?>

Working With PDO

PDO replaces all previous database interaction approaches. Using PDO, you could easily perform CRUD and related DBMS operations. In effect, PDO acts as a layer that separates database related operations from the rest of the code.

You might also like: Simple CRUD in PHP and MySQL

Connectivity

One of the most important benefits of PDO is the simple and very straightforward database connectivity. Consider the following code snippet that is used to set up connections with the database. Note that when the underlying DBMS changes, the only change that you need to make is the database type.

<?php

Class Connection {

private  $server = "mysql:host=localhost;dbname=cloudways";

private  $user = "root";

private  $pass = "";

private $options  = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);

protected $con;
 
          	public function openConnection()

           	{

               try

                 {

	        $this->con = new PDO($this->server, $this->user,$this->pass,$this->options);

	        return $this->con;

                  }

               catch (PDOException $e)

                 {

                     echo "There is some problem in connection: " . $e->getMessage();

                 }

           	}

public function closeConnection() {

   	$this->con = null;

	}

}

?>

In the above code snippet, notice that the DBMS is MySQL. However, if the DBMS changes to MS SQL Server, the only change will be the replacement of mysql with mssql.

Note: PDO can handle exceptions. Therefore, always wrap its operation in a try and catch block.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Creating a Table With PDO

In order to create a table, first declare a query string and then execute it with exec function as no data will be returned.

<?php

include_once 'connection.php';

try

{

     $database = new Connection();

     $db = $database->openConnection();

     // sql to create table

     $sql = "CREATE TABLE `Student` ( `ID` INT NOT NULL AUTO_INCREMENT , `name`VARCHAR(40) NOT NULL , `last_ame` VARCHAR(40) NOT NULL , `email` VARCHAR(40)NOT NULL , PRIMARY KEY (`ID`)) ";

     // use exec() because no results are returned

     $db->exec($sql);

     echo "Table Student created successfully";

     $database->closeConnection();

}

catch (PDOException $e)

{

    echo "There is some problem in connection: " . $e->getMessage();

}

?>

Inserting Data With PDO

In order to insert data into a table using PDO, first prepare the query using prepare statement. Next, this query is executed with the execute function. Note that this practice prevents SQL injection attacks.

<?php

include_once 'connection.php';

try

{

    $database = new Connection();

    $db = $database->openConnection();

    // inserting data into create table using prepare statement to prevent from sql injections

    $stm = $db->prepare("INSERT INTO student (ID,name,last_name,email) VALUES ( :id, :name, :lastname, :email)") ;

    // inserting a record

    $stm->execute(array(':id' => 0 , ':name' => 'Saquib' , ':lastname' => 'Rizwan' , ':email' => '[email protected]'));

    echo "New record created successfully";

}

catch (PDOException $e)

{

    echo "There is some problem in connection: " . $e->getMessage();

}

?>

Select Data With PDO

In order to select data, first create a query string and then execute it in a for each loop to fetch records from the table.

<?php

include_once 'connection.php';

try

{

    $database = new Connection();

    $db = $database->openConnection();

    $sql = "SELECT * FROM student " ;

    foreach ($db->query($sql) as $row) {

    echo " ID: ".$row['ID'] . "<br>";

    echo " Name: ".$row['name'] . "<br>";

    echo " Last Name: ".$row['last_name'] . "<br>";

    echo " Email: ".$row['email'] . "<br>";

    }

}

catch (PDOException $e)

{

    echo "There is some problem in connection: " . $e->getMessage();

}

?>

Update Data With PDO

In order to update a record in the table, first declare a query string and then execute it with exec function.

<?php

include_once 'connection.php';

try

{

     $database = new Connection();

     $db = $database->openConnection();

     $sql = "UPDATE `student` SET `name`= 'yourname' , `last_name` = 'your lastname' , `email` = 'your email' WHERE `id` = 8" ;

     $affectedrows  = $db->exec($sql);

   if(isset($affectedrows))

    {

       echo "Record has been successfully updated";

    }          

}

catch (PDOException $e)

{

    echo "There is some problem in connection: " . $e->getMessage();

}

?>

Delete Data With PDO

In order to delete a record from the table, first declare a query string and then execute it with exec function.

<?php

include_once 'connection.php';

try

{

     $database = new Connection();

     $db = $database->openConnection();

     $sql = "DELETE FROM student WHERE `id` = 8" ;

     $affectedrows  = $db->exec($sql);

   if(isset($affectedrows))

    {

       echo "Record has been successfully deleted";

    }          

}

catch (PDOException $e)

{

   echo "There is some problem in connection: " . $e->getMessage();

}

?>

Conclusion

PDO is the data accessing layer that greatly eases the process of connecting and working with databases. Perhaps, the best thing about PDO is the streamlined process of database migration. If you want speed up your PDO queries with iterators, check out this article by Michelangelo van Dam.

Host PHP Websites with Ease [Starts at $10 Credit]

  • Free Staging
  • Free backup
  • PHP 8.0
  • Unlimited Websites

TRY NOW

In this article, I introduced PDO and highlighted how you could perform CRUD actions using PDO in PHP. I also demonstrated setting up of PDO database connections. If you have questions or would like to add to the discussion, do leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Saquib Rizwan

Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now