How to Connect to a Remote Server in PHP
Database-driven websites rely on a remote server to store data, which is retrieved by connecting to that remote server and extracting information from the database(s) to display on a website. You can easily connect to any server.
Things You'll Need
- Text editor like Source Edit
- Document uploading software like FileZilla
- •Space on a Server with PHP and MySQL installed
Instructions
-
-
1
Create a variable to store the function that will access the remote server, as shown:
$dbc
EXPLANATION
A variable is any combination of letters or numbers preceded by a dollar sign. Create a variable that reminds you of what its function is, for example:
$name = "Eric Tilden";
$database = "Name of Database"; -
2
Set the variable equal to the mysql_connect() function.
$dbc = mysql_connect();
EXPLANATION
The mysql_connect() function opens or reuses a connection to a MySQL server. -
-
3
The mysql_connect() function has three required parameters. The first parameter is server. Most servers are named localhost. Check the documentation section of your host's server to find out the MySQL server name. The server can include a port number or a path to localhost.
$dbc = mysql_connect("localhost"); -
4
The second parameter is the username. Each database, if properly secured, has a username and a password associated with it. Separate the server and the username with a comma, as shown:
$dbc = mysql_connect("localhost", "username"); -
5
The third parameter is the password. Separate the username and password parameter with a comma.
$dbc = mysql_connect("localhost", "username", "password") -
6
Add an error statement after the function to make sure that you are connecting properly, as shown:
$dbc = mysql_connect("localhost", "username", "password") or die ("I cannot connect to the database for the following reason" . mysql_error());
EXPLANATION
If one of the parameters is incorrect, an error will appear on your browser indicated that the connection failed.
-
1
Tips & Warnings
After this connection is made, you can initiate another PHP function, called the mysql_select_db() function to select the specific database with which you wish to work. This makes sure that any other database accessible by this username and password is not accidentally accessed, or maliciously accessed.
mysql_select_db(database_name);