How to use mysqli_connect in PHP

MySQLi is the improved extension of MySQL. MYSQLi (“i” stands from “improved”) extension is used in PHP to provide an interface of MySQL Database.

In PHP version 5.5 or later MySQL_connect will not be usable. It means that MySQL is deprecated and will be removed in future. Alternative for PHP 5 version and later are MySQLi and PDO(PHP Data Objects).

So, in this tutorial we will see how to use mysqli_connect in PHP to connect with database.

MySQLi extension was specifically developed to take the advantage of new features available in MySQL Database Management System. MySQLi included with PHP 5.5 and later version.Therefore every PHP developer should try to use new MYSQLI API while connecting with database. There are lots of advantages of using MySQLi.

Advantages:

• Support prepared statements (Safe way of send data to mysql and protect from SQL injection)
• Object Oriented API
• Support complex transaction
• Support Multiple Statements

MYSQLi connection in PHP


MySQLi Connection with Object Method

<?php
$con = new mysqli('host_name','user_name','password','db_name');
?> 

MySQLi Connection with Procedural Method

<?php
$con = mysqli_connect('host_name','user_name','password','db_name');
?>

If your MySQL Port is different from default one (3306). Pass it as 5th parameter.
MySQLi Connection with Object Method and Port Number

<?php
$con = new mysqli('host_name','user_name','password','db_name', 'db_port');
?> 


MySQLi Connection with Procedural Method and Port Number

<?php
$con = mysqli_connect('host_name','user_name','password','db_name', 'db_port');
?>


Connection error checking with Object Method

<?php
$con = new mysqli('host_name','user_name','password','db_name');
if ($con-> connect_errno) {
  trigger_error('Database connection failed: '  . $con->connect_error);
}
?> 

Connection error checking with Procedural Method:

<?php
$con = mysqli_connect('host_name','user_name','password','db_name');
if (mysqli_connect_errno($con)) {
  trigger_error('Database connection failed: '  . mysqli_connect_error());
}
?> 

How to Setup MySQL Connection Using PDO in PHP

After reading this tutorial, I hope that you will be able to use it in your new Web application and existing s. If you have any queries feel free to write in comment box. 🙂 🙂

Leave a Comment