How To Create A Remote Database Connection Using PHP - Webcom Kenya

Contact Info

Garden Estate Road, Cedar Court, Block A Room A3 & A7

+254 720 727 460

info@webcomkenya.com

Howdy! How can we help you?
Categories
< All Topics
Print

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

  1. Open a new PHP file in your code editor.
  2. 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);

  1. 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());
}

  1. 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.

  1. 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.

Table of Contents