Every once in a while when working on a multitude websites, the need arises to allow one site to access the database of another site. This sounds like a daunting task but in reality it is not as hard as you may think.
First thing’s first, you need to allow remote access to your database. If you have cPanel installed on your server then this is a piece of cake. Here’s what to do:
The next step is to get your website to connect to the remote MySQL database and for this we will use some PHP code.
Create a new PHP file in your website’s hosting account and call is “connect.php”. We will use this file to connect to the database in order to use the remote data.
In “connect.php” type the following:
<?php
$connect = mysql_connect("host_name","mysql_user_name","mysql_password");
if (!$connect) {
die('Could not connect to the database: ' . mysql_error());
}
mysql_select_db("database_name", $connect);
?>
And save the file. Of course you would now have to write your code to pull the data from the database and format it how you would want. For example:
<?php
$get_data = mysql_query("SELECT * FROM database_table_name");
while($row = mysql_fetch_array($get_data)) {
echo '<p><strong>Name:</strong> ';
echo $row['fname'] . ' ' . $row['lname'] . '</p>';
}
mysql_close($connect); //Always close the connection to the database
?>
And there you have it. Remote connection to a MySQL database. I hope this helps you out there in cyber space.