How to Connect PHP to MSSQL Using PDO and ODBC?

Patricia Arquette
Release: 2024-11-07 00:33:02
Original
731 people have browsed it

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

Configure the configuration files as outlined below:

odbc.ini

[mssql]
Description             = MSSQL Server
Driver                  = freetds
Database                = XXXXXX
ServerName              = MSSQL
TDS_Version             = 7.1
Copy after login

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

freetds.conf

[mssql]
    host = XXXXXX
    port = 1433
    tds version = 7.1
Copy after login

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

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!

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