MySQLi Database Connection


Object Oriented PHP MySQLi Server and Database Connection

MySQLi Database connection by using Object Oriented Interface is an easy process. For this you will have to instantiate the mysqli class.

Here is the syntax to connect to MySQL server.

<?php
$conn = new mysqli('hostname', 'username', 'password', 'databasename');
//Check for database connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
?>

The '$conn' variable contains database connection object.

hostname - It is hostname of server or the IP address of your hosting account.
username - It specifies the MySQL username.
password - The password to access the database account.
databasename - It specifies the database name.

To know whether the database connection is successful or not, we have checked the database connection error in object oriented way. The connect_errno returns last error code number and connect_error returns the description of connection error.





Procedural PHP MySQLi Server and Database Connection

The mysqli_connect() function opens a new database connection in procedural way. The procedural way is similar to the old mysql connection.

<?php
$conn = mysqli_connect('hostname', 'username', 'password', 'databasename');
//Check for connection error
if(mysqli_connect_error()){
  die("Error in DB connection: ".mysqli_connect_errno()." - ".mysqli_connect_error());
}
?>

The $conn variable contains database connection object.

hostname - It is hostname of server or the IP address of your hosting account.
username - It specifies the MySQL username.
password - The password to access the database account.
databasename - It specifies the database name.

To know whether the database connection is successful or not, we have checked the database connection error in procedural way. If any error found, the mysqli_connect_error() returns the error description from the last connection error. Within the error block, the mysqli_connect_errno() returns last error code number.







Read more articles