As the internet and database technologies continue to evolve, PHP has become a popular server-side programming language tightly integrated with databases like MySQL. PDO (PHP Data Objects) is a database abstraction layer in PHP that offers a unified interface for database interactions. By using PDO, PHP applications can connect and interact with databases in a flexible and efficient manner. This guide will walk you through the process of compiling and installing the PDO MySQL extension.
First, you need to download the PHP source package, MySQL development packages, and the source code for the PDO MySQL extension. It is recommended to download these resources from the official website or from open-source mirror sites.
Extract the downloaded PHP source package and navigate to the extracted directory. In the terminal, execute the following command to enter the PHP extension directory:
<span class="fun">cd ext/pdo_mysql</span>
Run the following commands to compile and install the extension:
phpize
./configure
make
make install
Once the installation is complete, open the PHP configuration file (php.ini) and add the following line:
<span class="fun">extension=pdo_mysql.so</span>
Save the php.ini file and restart the PHP service:
<span class="fun">sudo service php-fpm restart</span>
Now that you have successfully installed the PDO MySQL extension, let's write a simple PHP script to test the PDO MySQL connection and query functionality:
<?php
$dsn = 'mysql:host=localhost;dbname=test';
$user = 'root';
$password = '123456';
try {
$pdo = new PDO($dsn, $user, $password);
$stmt = $pdo->query('SELECT * FROM users');
while ($row = $stmt->fetch()) {
echo $row['username'] . "
";
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Save the above code as test.php, and run the following command in the terminal:
<span class="fun">php test.php</span>
If everything works correctly, you will see the list of usernames fetched from the database, indicating that the PDO MySQL extension has been successfully installed and tested.
Through this guide, you have learned how to compile and install the PDO MySQL extension in your PHP environment and how to use it to connect and query MySQL databases. We hope this tutorial helps improve your PHP development skills, making your PHP applications more efficient and flexible.