Bootstrap FreeKB - PHP - Connect to mySQL or MariaDB
PHP - Connect to mySQL or MariaDB

Updated:   |  PHP articles

To be able to connect to MariaDB using PHP, PHP must be configured to use MySQLi or PDO. This tutorial will use PDO. Use apt-get or yum to install PDO and MYSQL for PHP.

yum install php-pdo
yum install php-mysql

 

Restart the web server. For example, if the web server is nginx, the ps command can be used to determine if your system is using init or systemd. If PID 1 is init, then you will use the service command. If PID 1 is systemd, then you will use the systemctl command.

If your system is using systemd, use the systemctl command to restart and enable nginx.

systemctl restart nginx
systemctl status nginx

 

If your system is using init, use the chkconfig and service commands to restart and enable nginx.

service nginx restart
service nginx status

 

If your system is using systemd, use the systemctl command to restart and enable php-fpm.

systemctl restart php-fpm
systemctl status php-fpm

 

If your system is using init, use the chkconfig and service commands to restart and enable php-fpm.

service php-fpm restart
service php-fpm status

 

Navigate to http://www.example.com/phpinfo.php and ensure PDO is listed.

 

Set the SELinux policy to allow HTTPD to connect to MariaDB.

setsebool -P httpd_can_network_connect_db=1 

 

If you have a firewall in front of your MariaDB system, such as firewalld, you will need to open the MariaDB port, which is 3306 by default.

firewall-cmd --add-port=3306/tcp --permanent
firewall-cmd --reload

 

Ensure /etc/my.cnf is bound to the IP address of your MariaDB system.

bind-address=10.17.6.56

 

The following PHP code is used to make a PDO connection to MariaDB.

<?php 
try {
   $con = new PDO("mysql:host=example.com", "username", "password");
   $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   echo "Successfully connected to MariaDB";
}

catch(PDOException $e) {
   echo "Connection failed: " . $e->getMessage();
}
?>

 

And here is how to make the connection to a certain database.

<?php 
try {
   $con = new PDO("mysql:host=example.com;dbname=MyDB", "username", "password");
   $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   echo "Successfully connected to MariaDB, using database MyDB";
}

catch(PDOException $e) {
   echo "Connection failed: " . $e->getMessage();
}
?>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter d14154 in the box below so that we can be sure you are a human.