How to connect to your MySQL database in PHP?

PHP // 980 views Add comments

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:


Free Web Hosting

$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.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

2 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

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Login