Installing PHP and connecting to MSSQL database under the Ubuntu operating system is one of the skills that many developers and system administrators need to master. This article will provide a detailed tutorial, including installing PHP, installing the MSSQL server driver, configuring PHP to connect to the MSSQL database, and providing corresponding code examples.
First, we need to install PHP and related extensions to be able to connect to the MSSQL database. Enter the following command in the terminal to install PHP and necessary extensions:
sudo apt update sudo apt install php php-mysql php-mbstring php-xml php-dev
You must install the MSSQL server-side driver to connect to the MSSQL database. The following are the installation steps:
Add Microsoft’s official package
sudo su curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list exit
Install SQL Server 2019 driver and related tools
sudo apt update sudo apt install unixodbc-dev msodbcsql17 mssql-tools
Configure the ODBC file/etc/odbcinst.ini
, add the following content
[MSSQL] Description = Microsoft ODBC Driver 17 for SQL Server Driver = /opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.8.so.1.1 UsageCount = 1
Install the MSSQL extension for PHP
sudo pecl install sqlsrv pdo_sqlsrv echo "extension=sqlsrv.so" | sudo tee -a /etc/php/7.4/cli/php.ini echo "extension=pdo_sqlsrv.so" | sudo tee -a /etc/php/7.4/cli/php.ini
Use the following code in the PHP file to connect to the MSSQL database:
<?php $serverName = "localhost"; $connectionOptions = array( "Database" => "database_name", "Uid" => "username", "PWD" => "password" ); //Establishes the connection $conn = sqlsrv_connect($serverName, $connectionOptions); if($conn) { echo "Connection established."; } else { echo "Connection could not be established."; die(print_r(sqlsrv_errors(), true)); } ?>
Through the guidance of this article, you will learn the complete steps to install PHP on the Ubuntu system and connect to the MSSQL database. Of course, in actual application, you may need to make adjustments and modifications according to specific circumstances. I hope this tutorial can help you successfully complete the required work.
The above is the detailed content of Complete tutorial on installing PHP and connecting to MSSQL database under Ubuntu. For more information, please follow other related articles on the PHP Chinese website!