Home  >  Article  >  Backend Development  >  How to Connect PHP to MSSQL via PDO ODBC?

How to Connect PHP to MSSQL via PDO ODBC?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-07 03:14:02743browse

How to Connect PHP to MSSQL via PDO ODBC?

Connecting PHP to MSSQL via PDO ODBC

Question:

Despite having ODBC available as a driver, attempts to establish a connection using new PDO("odbc:..." yield no response, hanging execution. How can PHP be successfully connected to an MSSQL database via PDO ODBC?

Answer:

Connecting PHP to MSSQL via PDO ODBC requires proper configuration of several files:

Configuration Files:

  • /etc/odbc.ini: Define connection details, including database name, server name, and TDS version.
  • /etc/odbcinst.ini: Specify the location of the Free TDS driver.
  • /etc/freetds/freetds.conf: Define the data source name (DSN) and connection parameters (host, port, TDS version).

Specific Configuration:

**[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

**[freetds.conf]**
[mssql]
host = XXXXXX
port = 1433
tds version = 7.1

Restarting Apache and PHP Code:

Execute service apache2 restart to restart Apache.

Create the PDO object as follows:

$pdo = new PDO("dblib:host=mssql;dbname=$dbname", "$dbuser","$dbpwd");

Note:

  • Adjust the TDS version in /etc/freetds/freetds.conf based on the MSSQL version.
  • Use the domain/username format for the username if necessary.
  • Verify successful connection by checking for "freetds" and an "mssql" section in phpinfo().

The above is the detailed content of How to Connect PHP to MSSQL via PDO ODBC?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn