How to connect remote MySQL database in PHP

Suppose you are working on some project and your code/application hosted on different hosting server and mysql database hosted on other different shared hosting server and you want to access your mysql database from application server remotely then this tutorial for you.

In some cases of development it requires to use multiple database in single project, So you need to access mysql server remotely from different server, By default For security reason remote access to MySQL database server is disabled in shared hosting. You need to enable remote MySQL access to connect MySQL database from the different server by adding the IP of other server.



Remote access will allow you access MySQL database from another server. This access is helpful when you want to connect multiple databases hosted on different server.This tutorial will help How to connect remote MySQL database in PHP.

Suppose your database hosted on shared hosting (SH-1) and your application on another host (SH-2). And you are looking solution to connect your SH-2 application server with SH-2 Mysql server then follow below steps.



Step-1: Login to your shared hosting cpanel.

Step-2: Under the Databases section, click on Remote MySQL®.

remote-mysql-connection-php
Step-3: Enter the IP address of application host server (SH-2) from where you need to access mysql database to authenticate connection for (SH-2).
remote-mysql-connection-php-1

Step-4: For making connection with database hosted in shared hosting server (SH-1) from another application server (SH-2). you just only add the host name of mysql server and database name with their username and password in php connection code. Now your mysql server (SH-1) will easily authenticate connection request from application server (SH-2).

<?php
$dbServerName = "example.com";
$dbUserName = "dbusername";
$dbPassword = "dbpassword";
$dbName = "dbname";
 
// make connection
$conn = new mysqli($dbServerName, $dbUsername, $dbPassword, $dbName);
 
// validate connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "DB Connected successfully";
?>

If connection will successful it’ll return message like “DB Connected successfully” and you’ll able to access mysql database and execute mysql queries from application server (SH-2) , If not then it’ll return connection error.

If you like this post please don’t forget to subscribe my public notebook for more useful stuff