How to connect to database in php using oop

Connect to database in php using oop


In this article, you will be learning how to connect database using oop in php (object oriented programming in php).

So, Let's begin with connecting your database in php oop where we will be seeing 2 example to connect database. 1. MySqli Object Oriented 2. MySqli Procedural.


Create a file DBConn.php and give MySqli Object Oriented Database connection in PHP

Example: MySqli Object Oriented in php

<?php

define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_DATABASE','adminpanel');

class DatabaseConnection
{
    public function __construct()
    {
        $conn = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);

        if($conn->connect_error)
        {
            die ("<h1>Database Connection Failed</h1>");
        }
        //echo "Database Connected Successfully";
        return $this->conn = $conn;
    }
}

?>


Example: MySqli Procedural Database Connection in php.

<?php

define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_DATABASE','adminpanel');

class DatabaseConnection
{
    public function __construct()
    {
        $conn = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);

        if (!$conn)
        {
            die ("<h1>Database Connection Failed</h1>". mysqli_connect_error());
        }
        echo "Database Connected Successfully";
return $this->conn = $conn;
    }
}

?>


Thank you.