PHP Code to Connect MySQL Database with MySQL, MySQLi Extensions

On 5/18/2014

Let's see how to connect to the MySQL Database with PHP. PHP comes with MySQL extension (API) to access MySQL DB. This extension is deprecated as of PHP 5.5.0, and will be removed in the future. So for higher versions of PHP we should go for the MySQLi or PDO_MySQL extension. We'll see the connection process with both MySQL and MySQLi extensions here.

1. Connect to DB with MySQL Extension

The connection is a two step process. First we should use mysql_connect() function to connect to the database. Next we should select the database with the function mysql_select_db().

Syntax for mysql_connect()

mysql_connect("server_name/ip_address","username","password");

Syntax for mysql_select_db()

mysql_select_db("mysql_database_name", mysql_handler);

Example 1

If we want to connect to the localhost server then we use,

<?php
//connect to mysql server
$con = mysql_connect("localhost","root","") or die('Error: ' . mysql_error());  //$con is the mysql_handler
//select db name
mysql_select_db("db_employee", $con);
?>
Example 2

Instead of the server name we can use the ip address of the server like this,

<?php
$con = mysql_connect("127.0.0.1","admin","user001") or die('Error: ' . mysql_error());
mysql_select_db("db_employee", $con);
?>

2. Connect to DB with MySQLi Extension

The MySQLi is the improved version of the MySQL extension and is designed to work with MySQL version 4.1.13 or above. We'll see how to use this extension for connecting the MySQL DB.

Here the process is even more simpler. There is no need to use two functions similar to the above example, one for connecting the server and another for selecting the database name. With the single mysqli_connect() function, we can accomplish both the tasks.

Syntax for mysqli_connect()

mysqli_connect("server_name/ip_address","username","password", "mysql_database_name");

Example
<?php
$con = mysqli_connect("localhost","root","user1","db_student") or die("Error " . mysqli_error($con));
?>

Note: If you use MySQL Database version 4.1.3 or above, then it is strongly recommended that you use MySQLi extension.


No comments:

Post a Comment

Contact Form

Name

Email *

Message *