How to Connect to the Remote MySQL Database using PHP


connect-to-remote-mysql-database-cpanel-php-codexworld

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-codexworld
  • 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-codexworld
  • To connect with the MySQL database hosted in the another server (Server A), use the following PHP code in Server A.
    <?php
    $dbServerName 
    "example.com";
    $dbUsername "exdbuser";
    $dbPassword "exdbpass";
    $dbName "codexworld";

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

    // check connection
    if ($conn->connect_error) {
        die(
    "Connection failed: " $conn->connect_error);
    }
    echo 
    "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.
    <?php
    /*
     * 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()) {
            echo 
    "id: " $row["id"]. " - Name: " $row["name"]. "<br>";
        }
    } else {
        echo 
    "0 results";
    }
    ?> 

1 Comment

  1. Hanhan Said...

Leave a reply

Connect With CodexWorld