How to Connect to the Remote MySQL Database using PHP

Some web projects are required accessing multiple databases on the different server. In that case, you should connect to the remote database from another server. For security reason remote access to MySQL database server is disabled. You need to enable remote MySQL access to connect MySQL database from the different 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 explains how to connect to the remote MySQL database using PHP.

Assume that the MySQL database is hosted on Server A and you want to connect this database from Server B using PHP script. So, the remote database connection process would be the following.

  • Log into the cPanel account of the web server, where the MySQL database is hosted (Server A).
  • Under the Databases section, click on Remote MySQL?.
  • remote-mysql-database-access-cpanel-semicolonworld
  • Enter the IP address of host server (Server B) from where the database will be accessed. Click on Add Host.
  • remote-mysql-database-access-cpanel-add-host-semicolonworld
  • To connect with the MySQL database hosted in the another server (Server A), use the following PHP code in Server A.
    $dbUsername "exdbuser";
    $dbPassword "exdbpass";
    $dbName "semicolonworld";

    // create connection
    $conn = new mysqli($dbServerName$dbUsername$dbPassword$dbName);

    // check connection
    if ($conn->connect_error) {
    "Connection failed: " $conn->connect_error);
    "Connected successfully";
  • Now you will able to access database tables of the remote database server. The following example script will fetch the users data from users table to the remote database.
     * get data from remote database table
    $sql "SELECT id, name FROM users";
    $result $conn->query($sql);

    if (
    $result->num_rows 0) {
    // output data of each row
    while($row $result->fetch_assoc()) {
    "id: " $row["id"]. " - Name: " $row["name"]. "<br>";
    } else {
    "0 results";

Related Articles

Comments 0