How to connect to MySQL Database using PHP

How to Connect to Your Database

The first thing you must do before you can do any work at all is to connect to the MySQL database. This is an extremely important step as, if you are not connected, your commands to the database will fail.

Good practice for using databases is to specify the username, password and database name first so that if you change any of them at a later date you will only have to change one line:

$username="username";
$password="password";
$database="your_database";

At this point you may be wondering if it is a security risk, keeping your password in the file. You don't need to worry, though, because the PHP source code is processed by the server before being sent to the browser so it is impossible for the user to see the script's source.

Next, you will need to issue the command to start a database connection:

mysql_connect(localhost,$username,$password);

This line tells PHP to connect to the MySQL database server at 'localhost' (localhost means the server that the site is running one. Another vital command is:

mysql_close();

This is a very important command as it closes the connection to the database server. Your script will still run if you do not include this command but too many open MySQL connections can cause problems for your account. It is good practice to always include this line once you have issued all your commands to the database, to keep the server running well.

After you have connected to the database server you must then select the database you wish to use. This must be a database to which your username has access. The following command:

@mysql_select_db($database) or die( "Unable to select database");

is used to do this. This tells PHP to select the database stored in the variable $database (which you have set earlier). If it cannot connect it will stop executing the script and output the text:

Unable to select database

This extra 'or die' part is good to leave in as it provides a little error control but it is not essential.

Now you have connected to the server and selected the database you want to work with, you can begin executing commands on the server.

  • 28 Utilizadores acharam útil
Esta resposta foi útil?