Monday 24 September 2018

Connecting MySQL database with MySQLi Object Oriented style

My previous article "How to connect MySQL database using MySQLi procedural function" demonstrates the use of MySQLi procedural function mysqli_connect() is used to connect with a MySQL database and MySQLi extension also provides an Object Oriented interface for connecting to database.


MySQLi Object Oriented Style     

To open a connection to MySQL database using MySQLi Object Oriented style we use constructor of mysqli class (mysqli::__construct) which is an alias of mysqli_connect(). On successful connection, it returns an object which represents the connection.

Note : It also returned an object on Failure also (With Object Oriented style). To check the failure of connection we can use either $con->connect_error or mysqli_connect_error().

Syntax : mysqli::__construct(host_name, username, password, db_name, port, socket)
  1. class mysqli {
  2. __construct ($host_name, $username, $password, $db_name, $port, $socket)
  3. }
  4. $con = new mysqli($host_name, $username, $password, $db_name, $port, $socket);

Parameters Description :
host_name : Specifies a host name or an IP address of MySQL server.
username : Specifies the MySQL username
password : Specifies the MySQL password
db_name : Specifies the default database to be used
port : Specifies the port number to connect to the MySQL server
socket : Specifies the socket name or named pipe

Example :
  1. <?php
  2. $host_name = "localhost";
  3. $username = "username";
  4. $password = "password";
  5. $database = "test";//database name
  6. // Create connection
  7. $con = new mysqli($host_name, $username, $password, $database);
  8. // Check connection
  9. if (!$con) {
  10. echo "Error: " . $con->connect_error; die;
  11. }
  12. echo "Connection to database : ".$database." created successfully on server : ".$con->host_info;
  13. ?>

Output : Connection to database : test created successfully on server : Localhost via UNIX socket

0 comments:

Post a Comment