Sometimes we need to connect one server file to another server database. This type of connection is called a Remote MySQL connection.
In this tutorial, we are going to see how to connect remote MySQL database in PHP.
Let’s dive in.
Suppose we have two servers Server 1 and Server 2 and we have to connect Server 2 file to server 1 database.
Server 1 is for Database.
Server 2 for Files.
Then we have to setup remote MySQL connection like this.
Step 1. Enable Remote MySQL
First login to cPanel of Server 1.
Go to Databases section >> Click on “Remote MySQL”
Add access host
1. Write remote server(Server 2) IP address here
2. Click on Add Host button.
That’s all.
Task for server 1 is completed.
Step 2. Create Connection On Sever 2
Now we have to setup a mysqli connection on server 2 to connect MySQL database of Sever 1 .
<?php
$hostname='Server 1 domain.com';
$username='Server 1 username';
$password='Server 1 password';
$dbname='Server 1 DB name';
$con = new mysqli($hostname,$username,$password,$dbname);
if ($con-> connect_errno) {
trigger_error('Database connection failed: ' . $con->connect_error);
}
?>
Now you can access to database of the remote server(server 1).
Conclusion
You have learned how to connect MySQL database from another server in PHP. If you have any questions, feel free to comment.