How to Connect PHP to MSSQL via PDO ODBC?

Patricia Arquette
Release: 2024-11-07 03:14:02
Original
743 people have browsed it

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
Copy after login

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");
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!