Installing and configuring PHP on an Ubuntu system to connect to an MSSQL database is a common task, especially when developing web applications. In this article, we will introduce how to install PHP, MSSQL extensions and configure database connections on Ubuntu systems, while providing specific code examples.
Install PHP
First, you need to make sure that PHP is installed on the Ubuntu system. You can install PHP through the following command:
sudo apt update sudo apt install php
Install MSSQL extension
Next, you need to install the MSSQL extension of PHP to connect to the MSSQL database. You can use the following command to install:
sudo apt install php-mssql
Edit the php.ini file
Open the PHP configuration file php.ini, you can use the following command:
sudo nano /etc/php/7.x/apache2/php.ini
Add the following line in the php.ini file to enable the MSSQL extension:
extension=php_mssql.so
Restart the Apache service
After saving and exiting the php.ini file, restart the Apache service to make the changes take effect:
sudo service apache2 restart
Now you can connect to MSSQL database using PHP code. Here is a simple example code:
<?php $serverName = "localhost"; $connectionOptions = array("Database" => "your_database", "Uid" => "your_username", "PWD" => "your_password"); // 通过sqlsrv_connect()函数连接数据库 $conn = sqlsrv_connect($serverName, $connectionOptions); if ($conn) { echo "Connection established. "; } else { echo "Connection could not be established. "; die(print_r(sqlsrv_errors(), true)); } // 查询数据 $sql = "SELECT * FROM your_table"; $stmt = sqlsrv_query($conn, $sql); if ($stmt === false) { die(print_r(sqlsrv_errors(), true)); } while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { echo $row['column_name'] . " "; } sqlsrv_free_stmt($stmt); sqlsrv_close($conn); ?>
Make sure to replace "localhost", "your_database", "your_username" and "your_password" in the example with your actual hostname, database name, username and password. The above code demonstrates the process of connecting to an MSSQL database and executing a simple query.
Through the above steps, you can successfully install and configure PHP on the Ubuntu system to connect to the MSSQL database, and use the provided code samples to perform database connection and query operations. Hope this article helps you!
The above is the detailed content of How to install and configure PHP on Ubuntu system to connect to MSSQL database. For more information, please follow other related articles on the PHP Chinese website!