Connecting to a database using MySql

November 16, 2007

Every time we work with MySql we have to connect to the database using some php functions. We may use this to connect different databases so I advice you to write this instructions in one separated file. This way you can easily edit it. Save this sequence in a file named connexion.php. For further applications just include this file using command include.

Look at the content of this file:

<?php$hostname="localhost";$username="root";

$password="pass";

$database="test";$connexion=mysql_connect($hostname,$username,$password)

or die ("Can't connect to the database!");

$db=mysql_select_db($database,$connexion)

or die ("Database not found!");

?>

mysql_connect() - we use this function for connecting to the database. This function has three parameters: the server name, the username and the password for connecting to the database. The $connexion variable can have two values: TRUE or FALSE depending on the MySql server connexion. In case it fails we will receive the message contained in the die() function.

mysql_select_db - this function will establish the database for connexion. This function has two parameters: the database name and the access identifier to the MySql server. The $db variable will contains the message in case the database is not found.

You can modify the content of the connexion file corresponding to your database configuration:

$hostname=the server address

$username=the username for connexion to the database

$password= the password for connexion to the database

$database=the database name

After all the operation made with the database we have to close the connexion using mysql_close() function.

mysql_close($connexion);

 

Post a comment

Name (required)

Mail (will not be published) (required)

Website

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word