PHP Scripts – WordPress Tutorials


Connecting MySQL database using PHP

You might be thinking of creating dynamic web pages in PHP. That’s brilliant because PHP is an Open Source programming language and is available to anyone who is interested.

To create dynamic web pages, the very basic step is that, one should have understanding of MySQL. In this lesson I‘ll teach you “How to build a connection between MySQL database using PHP

Whenever we are connecting our database, we need three things:

Hostname:
This is the name of your host. For example I am using APACHE in offline mode (not over a Hosting plan, using my computer as Server). Here the hostname is “Localhost”

Username:

This is the user name of your host (server), For example I am allotted “root” as my username.

Password:

Password of your server, that might “abcABC123”.

PHP provide us a built in function to establish a connection with MySQL database. This function is mysql_connect(). Mysql_connect() is with three parameters, that are described above, they are placed in same manner as I have written them above(hostname, username, password).

In my practices, I found that it is much better to have a connection.php file within a folder. In this way, if multiple pages within your site need to access the database, then you need to include the connection.php file.

Let’s move forward and create that file

FileName: connection.php

1
2
3
4
5
6
7
$hostName = 'localhost';

$userName = 'root';

$password = 'your_password';

$connection = mysql_connect($hostName, $userName, $password);

Now I want to make sure whether the connection is established successfully, if not, then stop the execution of the script. All that I need to do is to add some very simple statements. Look how I did:

FileName:connection.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$hostName = 'localhost';

$userName = 'root';

$password = 'your password';

$connection = mysql_connect($hostName, $userName, $password);

if( ! $ connection)

{

die('Some Error encountered because '.mysql_error());

}

Once you are done, execute your code.

For better practices I suggest you to close the database connection if it is not needed for the time being. With the simple mysql_close(); function, this can be achieved

FileName:connection.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$hostName = 'localhost';

$userName = 'root';

$password = 'your password';

$connection = mysql_connect($hostName, $ userName, $ password);

if( ! $ connection)

{

die('Error encountered with connection: '.mysql_error());

}

// your Script goes here

// finished with your process

// close the connection

mysql_close($connection);

Look how simple it is to establish a connection with MySQL database using PHP.

You can have all this in simple video tutorial

Related Posts


Categories: PHP, Web Development