Connecting to SQL Server using PDO in PHP 2019

PHP Data Objects (PDO)
In this content you will learn how to configure the Microsoft SQL Server Database connection driver and create a connection to this database using PHP Data Objects (PDO) and the PHP language.

To understand how a connection using PDO works, look at Figure 1:

Conexão utilizando PDO

The PDO extension defines a lightweight and consistent interface for accessing databases in PHP. Each database driver that implements it can use methods for communicating with the Database. Note that you cannot perform any database functions using the PDO extension by itself: You must use a database-specific PDO driver to access a server.

PDO provides a data access abstraction layer, which means that regardless of the database you are using, the functions for issuing queries and fetching data are the same. PDO does not provide a database abstraction, meaning it does not rewrite SQL or simulate missing features. You must use a full abstraction layer if you need this facility.

See Figure 2 for the drivers implemented in the PDO.


Drivers suportados pelo PDO conforme a documentação do PHP no site







class Conexao
   private static $connection;
   private function __construct(){}
   public static function getConnection() {
       $pdoConfig  = DB_DRIVER . ":". "Server=" . DB_HOST . ";";
       $pdoConfig .= "Database=".DB_NAME.";";
       try {
               $connection =  new PDO($pdoConfig, DB_USER, DB_PASSWORD);
               $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
           return $connection;
       } catch (PDOException $e) {
           $mensagem = "Drivers disponiveis: " . implode(",", PDO::getAvailableDrivers());
           $mensagem .= "\nErro: " . $e->getMessage();
           throw new Exception($mensagem);



See how we will use the connection class and make a query bringing some information from the Database:

READ  MongoDB: Scalable NoSQL Database

You May Also Like

About the Author: intermzv

Leave a Reply

Your email address will not be published. Required fields are marked *