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();
Mukesh Jakhar - PHP Web Developer
Mukesh Jakhar

This is Mukesh Jakhar. I’m a professional web developer with 3+ years experience. I am always ready for freelance work and i am writing blogs in my free time. I love to learn new technologies and share with others.

I founded PHPKIDA in September 2015. The focus of this website to provide web development tutorials of PHP, WordPress, CodeIgniter, Jquery, MySQL, HMTL, CSS etc and sharing solution to problems which i already solved.

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.