1. Introduction
MySQL is a popular and widely used relational database management system, and PHP is a popular server-side scripting language used to develop web applications. To connect PHP with MySQL, we need to install the MySQL extension for PHP. In this article, we will discuss how to install the MySQL extension for PHP7 on Linux.
2. Check PHP Version
Before proceeding with the installation, we should check the PHP version installed on our system. We can do this by running the following command in the terminal:
php -v
This will display the PHP version installed on our system. If we do not have PHP installed, we should follow the instructions to install PHP on our system.
3. Check MySQL Installation
We should also check if MySQL is installed on our system. We can do this by running the following command:
mysql -u root -p
This will prompt us to enter the MySQL root password. If we are able to log in to MySQL, it means that MySQL is installed on our system.
4. Install the MySQL Extension for PHP7
To install the MySQL extension for PHP7, we need to run the following command in the terminal:
sudo apt-get install php7.0-mysql
This will install the MySQL extension for PHP7. We can check if the extension is installed by running the following command:
php -m | grep mysql
If the output of this command is "mysql", it means that the MySQL extension is installed and enabled.
5. Restart Apache
After installing the MySQL extension for PHP7, we need to restart the Apache web server to apply the changes. We can do this by running the following command:
sudo systemctl restart apache2
6. Test the Installation
To test if the MySQL extension is working correctly, we can create a PHP file with the following code:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Replace the values of $username, $password, and $dbname with the appropriate values for your MySQL database. Save the file as "test.php" in the root directory of your web server (usually /var/www/html/). Then, navigate to http://localhost/test.php in your web browser. If the MySQL extension is working correctly, you should see the message "Connected successfully".
7. Conclusion
In this article, we discussed how to install the MySQL extension for PHP7 on Linux. We first checked the PHP version and MySQL installation, then proceeded to install the MySQL extension for PHP7. Finally, we tested the installation by creating a PHP script to connect to a MySQL database.