Connecting to a database server - The mysql_connect function
Before you can work with your MySQL database, you must connect to the MySQL database server from within your PHP script. In order to do this, you can use the PHP function mysql_connect whose syntax is as follows:
$connection = mysql_connect(servername, username, password)
- where $connection is the variable storing the connection if the connection is successful and taking the value FALSE otherwise.
- where servername is the string name of the server to which you are connecting (by default, this parameter is set to 'localhost:3306').
- where username is your connection username passed as a string.
- where password is your connection password passed as a string. By default, this parameter is set to '' (the empty string).
The parameters servername, username and password are defined from within your database managed server hosting software, at the moment your database is created (e.g. phpmyadmin). There you can set up users and determine their access authorizations.
Connecting to a database server - The mysql_close function
A MySQL database connection will be automatically interrupted when your PHP script terminates. However, it might happen that you wish to terminate it earlier during the execution of your PHP scripts. In that case, you shall use the PHP function mysql_close. Its PHP syntax is as follows:
mysql_close($connection)
- where $connection is the connection variable as defined by the function mysql_connect.
We have seen that the variable $connection takes the value FALSE when the connection fails. In this case, it is customary to interrupt the PHP script with the PHP function die; indeed, it allows to permanently interrupt the execution of the script while printing a message on the page. Its PHP syntax is as follows:
die($message)
- where $message is the string message that you want to be returned when the mysql connection is unsuccessful.
Using the previous die() PHP function, you can therefore insert the following line of code when writing your PHP scripts:
Learn the PHP code
|
<?php $connection = mysql_connect(servername, username, password); if (!$connection) die('An error has occured during the connection'); ?> |
When you want to manipulate your MySQL databases, you first need to establish a connection to your MySQL database server with the function mysql_connect.
This connection is automatically terminated once your PHP script ends, but can also be interrupted within the PHP script with the function mysql_close.
You can use the PHP function die() to print a message and permanently interrupt a PHP script; in particular, this function is usually used to deal with the case where a database server connection has been unsuccessful.
Next tutorial: Creating or deleting a MySQL database
Previous tutorial: SQL queries in PHP
Back to computer forums
