When developing with PHP7, interaction with MySQL databases is common. The mysqli extension is the official recommended interface for MySQL in PHP, offering extensive features and performance improvements. This article will guide you through installing and enabling the mysqli extension in PHP7.
Before installing the mysqli extension, make sure PHP7 is installed correctly. You can check the PHP version by running the following command in the terminal:
<span class="fun">$ php -v</span>
If the version starts with 7, PHP7 is installed.
The mysqli extension is usually included in PHP7 by default. You just need to enable it in the php.ini configuration file.
First, locate the php.ini file path by running:
<span class="fun">$ php --ini</span>
Open the displayed php.ini file and find the line:
<span class="fun">;extension=mysqli</span>
Remove the semicolon “;” to enable it:
<span class="fun">extension=mysqli</span>
Save and close the file.
Then restart your web server or PHP-FPM service to apply the changes.
To confirm the mysqli extension is enabled, create a test script.
Create a file named test_mysqli.php with the following content:
<?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
if (!$conn) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
echo 'Connected to MySQL successfully';
mysqli_close($conn);
?>
Replace 'localhost', 'username', 'password', and 'database' with your actual database credentials.
Save the file, then run the script in the terminal:
<span class="fun">$ php test_mysqli.php</span>
If it outputs "Connected to MySQL successfully," the mysqli extension is working properly. Otherwise, check your configuration and connection details.
Following these steps, you can easily install and configure the mysqli extension in PHP7, enabling efficient MySQL database operations. In practice, it’s recommended to use prepared statements to enhance security and manage database connections effectively for better performance.