Posted on Thursday, 27th December 2007 by tutorials007

In this tutorial I’ll explain you how to connect to your MySQL database in PHP.  MySQL databases are used almost always in our coding life. So if you just started with MySQL, or if you want to start, this is the right tutorial for you.

Let’s begin

This is the whole code:

<? $host = “localhost“;
$user = “
username“;
$password = “
password“;
$name = “
database name“;
mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
?>

So in the code above you can change only red text (localhost,username,password,database name).
Let me explain:

$host - this is your database host. Usually it’s localhost but to be sure ask your server administrator which is it.
$user - this is your mysql username.
$password - this is your mysql password
$name - this is your database name.

The code:
This part of code just sets variables for the easier usage:

$host = “localhost”;
$user = “username”;
$password = “password”;
$name = “database name”;

This part of code connects to the database:

mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());


At the end:
You can put this code in one php page and call that page ex. dbconnect.php . After that you should include this page in every php page that uses your database.

Posted in Archive | Comments (3)



3 Responses to “How to connect to your MySQL database in PHP?”

  1. soes Says:

    good information, thank’s

  2. Dedicated Says:

    Thanks for this helpful posts

  3. Sanjeev Says:

    Nice Post. This is useful for everyone. Thank you very much.

Leave a Reply