How to Configure PHP for a Remote Database Access
PHP is a programming language used to make dynamic websites. PHP is a free tool, and it is normally run on Apache Internet hosting servers. Apache servers that host PHP and MySQL are more affordable than other host services, so it's a popular web development language. When you query a MySQL database server, you first need to establish the connection and provide the necessary credentials. These credentials and the connection allow you to call queries and tables on the database server.
Instructions
-
-
1
Open the PHP file you want to edit in a text or HTML editor. PHP is plain text, so any application that allows you to edit plain text can be used for PHP.
-
2
Start the PHP code. Whenever you create PHP code blocks in your web page files, you need to open and close the code with the PHP indicators. These characters are "<?" and "?>".
-
-
3
Set up the variables for the user name, password and database server. These three variables are needed to attach to the database server. The following code assigns the server variable to localhost and uses the "root" user name with a password:
<?
$dbserver = 'localhost';
$dbusername = 'root';
$dbpassword = 'password';
?> -
4
Use "mysql_connect()" to open the database server connection. If the connection fails, the "die" command prints an error to the page. The following code opens the database server connection using the variables setup in Step 3:
<?
$dbserver = 'localhost';
$dbusername = 'root';
$dbpassword = 'password';
$conn = mysql_connect($dbserver, $dbusername, $dbpassword) or die ('An error occurred when connecting to the server');
?> -
5
Connect to the database. The server connection is open, but you still need to open the database. The last line of code needed is the "mysql_select_db()" function that points the connection created in Step 4 to the database you want to query. The code to accomplish this is below:
<?
$dbserver = 'localhost';
$dbusername = 'root';
$dbpassword = 'password';
$conn = mysql_connect($dbserver, $dbusername, $dbpassword) or die ('An error occurred when connecting to the server');
mysql_select_db("my_database");
?> -
6
Save this file and test it using your web browser. If the code is successful, the web page will be blank. If an error occurs, "An error occurred when connecting to the server" is displayed.
-
1