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();

Leave a Reply

Related Posts: You may like

Extract Total Number of Image And Missing Alt Attribute using php

How to extract Heading tags using PHP from string

How to remove whitespace from string using php

Remove All Special Characters From String PHP

PHPKIDA Offering Free Tools:


Download Instagram Videos & Photos.

Download Now


Real Time Currency Converter

Convert Now


Robots.txt File Creater

Create Now


Compress yout HTML Code

Minify Now


Compress yout CSS Code

Minify Now


Compress yout JavaScript Code

Minify Now

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.