Current course:

PHP - Connecting to a database

The Code:

$db = mysql_connect("localhost","username","password");
mysql_select_db("da_interactive", $db);


In line 1, we set a variable called "$db" to our connection. The connection is made up of 4 parts. First, is "mysql_connect", which is what we use to connect to a mysql database. After that, we send three parameters to use for our connection. The first, is our host - in this case, it's "localhost", but it can also be a domain or an IP address. After that, we have our username and password.

In line 2, we select the database we'd like to use. This is necessary, because you could have more than one database per user on a specific host. Even if you only have one database, this line is still required. The first parameter is the database name, and the second is the connection (which we've set to our $db variable in the line above).


After opening a connection to a database, you should always close it using mysql_close(). This is usually done at the bottom of the page, as once it's closed, you can no longer use php/mysql to work with the database.