Connect PHP to MSSQL via PDO ODBC
When using the PDO ODBC driver to connect PHP to a MSSQL database, it's essential to ensure proper configuration. This involves setting up multiple configuration files:
1. Configuration Files:
-
odbc.ini: Defines the connection to the database.
-
odbcinst.ini: Specifies the driver location.
-
freetds.conf: Defines the DSN (Data Source Name) for connecting to MSSQL.
2. Package Installation:
- Install unixodbc and freetds, which may require specific package names in your operating system (e.g., tdsodbc in Ubuntu).
3. odbc.ini Configuration:
[mssql]
Description = MSSQL Server
Driver = freetds
Database = XXXXXX
ServerName = MSSQL
TDS_Version = 7.1
Copy after login
- Replace XXXXXX with your database name.
- Ensure the Driver value matches the driver defined in odbcinst.ini.
- The ServerName should match what you defined in freetds.conf.
- Set TDS_Version to match the version specified in freetds.conf.
4. odbcinst.ini Configuration:
[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
- Adjust the Driver and Setup paths based on your system's architecture.
5. freetds.conf Configuration:
[mssql]
host = XXXXXX
port = 1433
tds version = 7.1
Copy after login
- Replace XXXXXX with your MSSQL server's IP or hostname.
- Set port to 1433 or the appropriate port.
- Adjust tds version to match your MSSQL version.
6. PHP Code Modifications:
- In your PHP code, create the PDO object using dblib as the DBNAME:
$pdo = new PDO("dblib:host=mssql;dbname=$dbname", "$dbuser","$dbpwd");
Copy after login
- Specify the domainusername format for the username if necessary.
7. Apache Restart:
- Restart Apache after making all these changes.
Verification:
- Execute phpinfo() to check if the setup is successful. Search for "freetds" in the output. It should show an "MSSQL" section with "freetds" as the "Library Version."
The above is the detailed content of How to Connect PHP to MSSQL using PDO ODBC?. For more information, please follow other related articles on the PHP Chinese website!