When connecting PHP to a MySQL database, sometimes the MySQL extension fails to enable. This is usually due to missing libraries or incorrect configuration. This article walks you through the steps to identify and fix this issue, ensuring PHP can properly access your MySQL database.
First, verify whether your PHP environment has the MySQL extension installed and enabled. You can check this by running the following PHP code to display PHP configuration information:
<?php
echo phpinfo();
?>
After running this, look for sections related to "mysqlnd" or "mysqli" extensions. If found, it means the MySQL extension is installed and enabled. If not, continue with the following steps.
If the MySQL extension is missing, the system may lack the necessary MySQL client libraries. On Ubuntu, for example, you can install them using:
sudo apt-get install libmysqlclient-dev
After installation, open your PHP configuration file php.ini to check if the MySQL extension is enabled.
Open the php.ini file and look for the following lines:
;extension=mysql.so
extension=mysqli.so
It is recommended to comment out extension=mysql.so and enable extension=mysqli.so, as mysqli is the improved MySQL extension supporting more features and better performance.
After making changes, restart your web server to apply them. Common restart commands are:
sudo service apache2 restart
If you use Nginx, restart it by running:
sudo service nginx restart
PHP failing to enable the MySQL extension is usually caused by missing libraries or incorrect php.ini configuration. Always back up your php.ini before making changes to prevent unexpected issues. Following these steps helps you effectively diagnose and resolve PHP MySQL extension problems, ensuring your system runs smoothly.