How To Connect To Remote Database Using Php

How To Connect To Remote Database Using Php

Often times I have the need or requirement to connect to a database from my local computer remotely. I like to use a database management to run queries, view some of the tables, extract data, or whatever else comes from the project I’m working on. I also might be writing a standalone mobile or desktop application that needs access to a database hosted anywhere not on my computer.

How can you connect to a MySQL database using PHP?

By default, MySQL disables remote access to its database for security reasons so, before our PHP code can connect to the database we need to whitelist us. We do this by allowing certain IP addresses or hostnames access to the database. If your database server is using cPanel then enabling remote MySQL access is very easy.

Enable Remote MySQL Access in cPanel

  1. Log into the cPanel account of the web server, where the MySQL database is hosted.
  2. Under the Databases section, click on Remote MySQL. Remote MySQL DB access
  3. Enter the IP address of host server from where the database will be accessed. You could also use your domain, example.com. Click on Add Host.

    Enable remote MySQL cPanel

  4. Use the following PHP code to connect to your database server.

    <?php
    $dbServerName = "example.com";
    $dbUsername = "user";
    $dbPassword = "password";
    $dbName = "database";
    
    // create connection
    $conn = new mysqli($dbServerName, $dbUsername, $dbPassword, $dbName);
    
    // check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    ?>
    

But wait, there’s more!

As I mentioned before I use a database management tool such as TablePlus to connect to my databases from my local computer. If you want to do this too, then just do the first 3 steps and use your computer’s local IP.

Final Note, Check Your Firewall

MySQL is served on port 3306 so make sure your database server is not blocking incoming requests to this port if you are NOT using cPanel.