How to create a remote database connection using PHP
Below is a step guide on how to create a remote database connection using PHP:
Remember before you write any PHP script to create a remote database connection, you must allow and give permission of the IP address or the server name that is trying to connect to the database remotely. Otherwise without the remote permission the connection will not work. See My article on how to how to allow remote database connect in cpanel
- Open a new PHP file in your code editor.
- Use the PHP built-in functionÂ
mysqli_connect()
 to establish a connection to the remote database. This function takes four parameters: the host name or IP address of the server, the username of the database user, the password of the database user, and the name of the database you want to connect to. Here’s an example:
$host = ‘remote.host.com’;
$user = ‘remote_user’;
$password = ‘remote_password’;
$dbname = ‘remote_database’;
$connection = mysqli_connect($host, $user, $password, $dbname);
- Check if the connection was successful using theÂ
mysqli_connect_error()
 function. If the connection was not successful, you can use theÂmysqli_connect_errno()
 function to get the error code and message. Here’s an example:
if (mysqli_connect_error()) {
die(‘Connect Error (‘ . mysqli_connect_errno() . ‘) ‘ . mysqli_connect_error());
}
- Once you have established the connection, you can execute SQL queries using theÂ
mysqli_query()
 function. Here’s an example:
$query = “SELECT * FROM users”;
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo $row[‘name’] . ‘<br>’;
}
In this example, we select all the users from the “users” table and display their names using a while loop.
- When you’re finished with the connection, you should close it using theÂ
mysqli_close()
 function. Here’s an example:
mysqli_close($connection);
That’s it! With these steps, you should be able to create a remote database connection using PHP.