Log In | Register | March 2, 2024


PHP Programming - November 4, 2010

PHP Connect to MySQL Database

Connecting to a MySQL database is a simple process requiring only 2 functions. 1 function to connect to the server and 1 function to connect to the desired database. The functions used to establish a MySQL connection are mysql_connect() and mysql_select_db().

First lets start by seeing a sample of the connection code and then I’ll go through and explain each function.

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());

First thing you will notice is that we assigned the mysql_connect() function to the variable link. The mysql_connect() function accepts 3 parameters. The hostname, then the username, and finally the password for the database. The information needs to be placed in exactly that order comma delimited. The end boolean result is then assigned to the variable $link.

Next we made an if check to see if the link variable is false. If it is false we stopped the script from running any further using the PHP die() function. We also returned the MySQL error we retrieved if the connection returned false using the function mysql_error().

If the link variable is true we then used the mysql_select_db() function which is used to select the database you want to connect to. This function can accept 2 parameters but only one is really needed which is the database name. The 2 parameters that this function can take are the database name, and the database link you established. We set this function to the variable db_selected in order to store the boolean result of true or false whether it connected or not. If it did not connect we simply ended the script with the die() function returning the MySQL error for debugging.

Thats all you need to establish a connection to the MySQL database using your PHP Script. Let me know if you have any questions in the comments below.

Post By: | FavoriteLoadingAdd to favorites


PC Guy
Friday, November 26, 2010

I found this data is very useful. Thank you for sharing. Do you mind if I republish a few paragraphs written in this article in our site if it’s disclosed you as the writer and links back to your site? Thank you!

Frank Perez
Saturday, March 12, 2011

Go for it.

Leave a Comment

Need Help? Ask a Question

Ask anything you want from how to questions to debug. We're here to help.

You Must Be Logged In To Post A Question.

Log In or Register