Wednesday, October 18, 2017

Using PDO MSSQL in PHP


This tutorial will guide you how to use PDO in order to access Microsoft SQL Server.

Step 1: Install Microsoft ODBC 11 driver for MSSQL
Link download :
https://www.microsoft.com/en-us/download/details.aspx?id=36434

Step 2: Download Microsoft Drivers for PHP for SQL Server

Link download :
 https://www.microsoft.com/en-us/download/details.aspx?id=20098&e6b34bbe-475b-1abd-2c51-b5034bcdd6d2=True

Note: Download version 4.0 if you use PHP 7

Step 3: Config file PHP.ini
Note: if you use WAMP Server, you need to edit file php.ini inside the bin directory of apache

Add these lines into the php.ini file :
extension=php_pdo_sqlsrv_7_nts_x64.dll

extension=php_pdo_sqlsrv_7_ts_x64.dll

Step 4: Ensure Driver is install successfully
Can check via phpinfo() function, and search for sqlsrv services.

Step 5: Example for using with Slim Framework

// Declare config
$app = new \Slim\App($config);
$container = $app->getContainer();
// Config Database
$container['db'] = function () {
$odbc="odbc:Driver={SQL Server};Server=localhost;Database=OracleDB;";
return new PDO( $odbc , "username" , "password");
};

// Using
$query = "SELECT * FROM Users WHERE LoginName = 'lieubv' ";
$conn = $this->c->db;
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->query( $query );

echo "<pre>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
       print_r($row);
}
echo "</pre>";

die();


Happy Coding!

No comments:

Post a Comment

Sublime Text 3 Usage

1. Download and install sublime 2. Install some essential packages: - Seti.sublime-theme  : theme beautiful - HTML-CSS-JS Prettify (nee...