How do I connect to a database with PHP?

To connect to a database you first open a so-called handle to mysql. Then you select the database itself. You do this with the commands mysql_connect and mysql_select_db:

$dbh = mysql_connect("localhost","login","password") or die(mysql_error()); mysql_select_db("database",$dbh);

In this example, replace database, login and password with the details you chose while creating the database via the control panel.

Are you done with the database in your script? Then it's good practice to close it again:

mysql_close($dbh);

Want to know more about storing and retrieving information? Check out the PHP website.

Related articles