How to connect to MariaDB in PHP

Home > Search > How-to

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.

[root@server1 ~]# yum install php-pdo
[root@server1 ~]# yum install php-mysql


Rstart the web server. For example, if the web server is nginx:

[root@server1 ~]# systemctl restart nginx
[root@server1 ~]# systemctl status nginx


If using PHP FPM, restart PHP.

[root@server1 ~]# systemctl restart php-fpm
[root@server1 ~]# systemctl status php-fpm


Navigate to and ensure PDO is listed.


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

[root@server1 ~]# setsebool -P httpd_can_network_connect_db=1 


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

try {
   $con = new PDO(";dbname=MyDB", "username", "password");
   echo "Successfully connected to MariaDB";

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


If the connection is successful, "Successfully connected to MariaDB" will be displayed.


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

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