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

How to Connect PHP to MSSQL Using PDO and ODBC?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-07 00:33:02658browse

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:

  • /etc/odbc.ini: Defines a connection to the MSSQL server.
  • /etc/odbcinst.ini: Specifies the driver location for Free TDS connections.
  • /etc/freetds/freetds.conf: Defines the DSN (Data Source Name) for the MSSQL connection.

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:

  • Replace dbname with the name of your database.
  • Format your username as domainusername if necessary.

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!

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