Home > Article > Backend Development > How to Connect PHP to MSSQL Using PDO and ODBC?
Connect PHP to MSSQL via PDO ODBC
To establish a connection between PHP and an MSSQL database using PDO and ODBC, there are crucial configurations that must be in place.
Configuration Files
Ensure you have the necessary configuration files set up:
Linux Package Installation
Install unixodbc and freetds packages. For Ubuntu, execute:
apt-get install unixodbc tdsodbc
Configure the configuration files as outlined below:
odbc.ini
[mssql] Description = MSSQL Server Driver = freetds Database = XXXXXX ServerName = MSSQL TDS_Version = 7.1
odbcinst.ini
[freetds] Description = MS SQL database access with Free TDS Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so Setup = /usr/lib/i386-linux-gnu/odbc/libtdsS.so UsageCount = 1
freetds.conf
[mssql] host = XXXXXX port = 1433 tds version = 7.1
Restart Apache after making these changes.
PHP PDO Connection
Create a PDO object using the following syntax:
$pdo = new PDO("dblib:host=mssql;dbname=$dbname", "$dbuser","$dbpwd");
Note:
If these steps are followed correctly, searching for "freetds" in your phpinfo() should reveal an mssql section with freetds listed as the Library Version, signifying a successful connection.
The above is the detailed content of How to Connect PHP to MSSQL Using PDO and ODBC?. For more information, please follow other related articles on the PHP Chinese website!