MySQLi Database Connection

MySQLi extension can be used either in a procedural or object-oriented way. In a procedural way functions are called, while in an object-oriented way a class object is used to perform operations on a database. MySQLi supports CRUD queries, prepared statements, multiple statements, and SQL operations.



Object-oriented PHP MySQLi Server and Database Connection

MySQLi Database connection by using an object-oriented interface is an easy process. The object-oriented interface shows functions grouped by their purpose, making it simpler to get started. For this you will have to instantiate the mysqli class.

Here is the syntax to connect to the 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 a database connection object.

hostname: It is the hostname of the 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 an 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

Users migrating from the old mysql extension may prefer the procedural interface. Procedural interface has functions to perform tasks similarly as old MySQL provides, only in the place of 'mysql' prefix, 'mysqli' prefix is used, like - mysqli_connect, mysqli_fetch_object.

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 a database connection object.

hostname: It is the hostname of the 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 the procedural way. If any error is 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


General Knowledge



Learn Popular Language