Skip to content

How to use MySQLi_connect in PHP

The MySQLi extension was developed to take advantage of new features found in MySQL systems versions 4.1 and Above. MySQLi is also sometimes known as the MySQL improved extension.The MySQLi extension is included with PHP versions 5 and later.

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use this extension.

The MySQLi extension has a number of benefits, the key enhancements over the MySQL extension listed below

  • Object-oriented interface as well as this extension also provides a procedural interface
  • Support for Prepared Statements
  • Support for Multiple Statements
  • Support for Transactions
  • Enhanced debugging capabilities
  • Embedded server support

So Today I am going to Write About Connecting to MySQL Server using PHP’s MySQLi Extension.

mysqli_connect() function is used to connect to database,this function returns a link identifier On success, that you can use in other MySQLi functions. On failure, it will throw an error.

MySQLi connection with the object method

$link = new mysqli('localhost', 'root', 'password', 'database_name'); 

MySQLi connection with the procedural method

$link = mysqli_connect('localhost', 'root', 'password', 'database_name'); 

If your MySQL port is different from default one (3306), you need to give the port number as the fifth parameter.

MySQLi connection with the Port Number

//MySQLi connection with the procedural method and port
$link = mysqli_connect('localhost', 'root', 'password', 'database_name',3307);
//MySQLi connection with the object method and port
$link = new mysqli('localhost', 'root', 'password', 'database_name',3307);  

mysqli_connect() throws an error at failure and mysqli_connect_error() stores the error in last call to mysqli_connect(). If there is no error, it returns NULL.

Connection error checking

// OPPs method
$sql = new mysqli('hostName', 'userName', 'password', 'DBName');
 
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

//procedural method
$con = mysqli_connect("hostName","userName","password","DBName") or die("Some error occurred during connection " . mysqli_error($con));
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments