php mysqli conneection object oriented

Today we are show you how to create database connection with object oriented PHP features with mysqli type connection using php class and function.
Here we are also going to display all the data of a table this table available in my local system database. We had done this before using a procedural way, but in this tutorial we are going to try it using object oriented PHP features.

Step 1: First of a you should create a php file “connect.php” and copy past below code inside connect.php file and save. Then create class “createCon” define all required variables, create a construct, inside construct create a connection.

class createCon  {
    var $host = 'localhost';
    var $user = 'root';
    var $pass = '';
    var $db = 'test';
    var $myconn;

    function __construct() {
        $con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
        if (!$con) {
            die('Could not connect to database!');
        } else {
            $this->myconn = $con;
            //echo 'Connection established!';
        return $this->myconn;

    function close() {
        echo 'Connection closed!';

class fetchData{
    private $obj;
    function __construct(){
        $this->obj = new createCon();
    function fetchTestData()
        //$obj = new createCon();
        $query = 'SELECT * FROM  `tempdata`';
        $result = mysqli_query($this->obj->myconn, $query);
        if($numrows = mysqli_num_rows($result))
            while ($row = mysqli_fetch_assoc($result))
                echo "<br>".$row['name'];
                echo "<br>".$row['email'];

Step 2: Just create one more file with php extension such as “index.php” inside index.php file include the connect.php file and create object of fetch-data class and call the function using class object which use to show test data from a table.

include 'connect.php';

$Obj = new fetchData();
About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.