Connect to Database using Php PDO

Database Connection using Php PDO 

Connect to Database with PDO Line of code for connect to database.
When we want to change database, we just rewrite one line code.
Not all code. Below is Php script to connect to several database:

   <?php
                // for MySQL
                $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);    
                // for SQLite
                $conn = new PDO("sqlite:$db");   
                // for postgreSQL
                $conn = new PDO("pgsql:host=$host dbname=$db", $user, $pass);
        ?>

Looking the script below:

      <?php
                // configuration variables
                $dbtype     = "sqlite";
                $dbhost     = "localhost";
                $dbname     = "test";
                $dbuser     = "root";
                $dbpass     = "admin";
                $dbpath     = "c:/test.db";      
                // switching for database selection
                switch($dbtype){
                  case "mysql":
                    $dbconn = "mysql:host=$dbhost;dbname=$dbname";
                    break;

                  case "sqlite":
                    $dbconn = "sqlite:$dbpath";
                    break;

                  case "postgresql":
                    $dbconn = "pgsql:host=$dbhost dbname=$dbname";
                    break;
                }        
                // database connection using PDO
                $connection = new PDO($dbconn,$username,$password);
     
        ?>
   
This is sample script to create database connection using PDO.
It is more portable, because when we change database, we just change at configuration part .


2 comments:

oliver said...

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. Source: https://www.cloudways.com/blog/introduction-php-data-objects/

Suba said...

PHP is an excellent programming language used widely by most of the web developers. Your article made me learn PHP certification. Thanks for the motivation.
Regards:
Best PHP training in chennai
PHP Training