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

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 

 

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

<?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";
}

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 f260a in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |