Setup MSSQL PDO for PHP 7.2 / 7.x

By | July 19, 2018

Bismillahi-r-Rahmani-r-Rahim (In the name of Allah, the most Compassionate, the most Merciful)

Assalamu alaikum wa rahmatullahi wa barakatuh (May the peace, mercy, and blessings of Allah be with you)


This is the ad hoc tutorial on how to enable PHP PDO for MSSQL. First, we will download and install necessary files and packages. Then we will make the needed system configurations. Finally, we will install the pdo_sqlrv package, create the PHP configuration file and test the connection with PDO to MSSQL server.

Below content is complementary to the video tutorial above.

Download and install necessary files and packages:

yum install -y curl gcc-c++
curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/mssql-release.repo
yum remove unixODBC-utf16-devel
ACCEPT_EULA=Y yum install -y msodbcsql mssql-tools
yum install -y unixODBC-devel

Make the necessary configurations:

echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc
pear config-set php_ini `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"` system

Install the php mssql pdo packages:

pecl install sqlsrv && pecl install pdo_sqlsrv

Create the php configuration file:

sed -i 's/extension="pdo_sqlsrv.so"/ /g' /etc/php.ini
sed -i 's/extension="sqlsrv.so"/ /g' /etc/php.ini
echo ''';Enable pdo_sqlsrv extension module
extension=pdo_sqlsrv.so
extension=sqlsrv.so
'
'' > /etc/php.d/pdo_sqlsrv.ini

Restart the necessary services:

service httpd restart && service php-fpm restart

Test the installed MSSQL PDO (additionally, see the output of phpinfo()):

php -r '$con=new PDO("sqlsrv:Server=192.168.74.129,1433;Database=test","test","test");$stmt=$con->prepare("SELECT @@Version as SQL_VERSION, CURRENT_TIMESTAMP as TIME");$stmt->execute();$stmt->setFetchMode(PDO::FETCH_ASSOC);var_dump($stmt->fetch());'

Related resources: