Back to top

Object Oriented Programming with PHP and MYSQLI

This article demonstrates object oriented programming with PHP and MYSQLI. 

Color Codes:

  • Class in teal
  • Function in green
  • File in red
  • Comments in blue

Scenario:

A database named oop has table titled oop_table with following structure:

Table name: oop_table

Table structure:

Field Type Remarks
id int(11) primary key with auto increment
name varchar(50)  

Database details:

Parameter Value
Host localhost
Database name oop
Username root
Password root

 

Now, we need to design php files to perform following types of queries in the database:

Query Detail
Create Creates a single row in the database
Read Retrieves a single row from the database.
  Retrieves all rows from the database.
Update Updates data in a single row of the database.
Delete Deletes a single row of data in the database.

Collectively these four activities are known as CRUD.

And of course, we need a class file to connect to the database itself at the first place.

 

We will create separate class files to perform each of the above queries.

Class Files:

Class file Objective CRUD Activity
dbConnect.php connect to database  
addClass.php add data to database Create
editClass.php edit data in database Update
selectClass.php select a single row of data in database for a given id Read
selectAllClass.php select all rows of data in database Read
deleteClass.php delete a single row of data in database with a given id Delete

All the above files will be kept in a separate folder called "classes"

 

Rest of the files:

File Description
index.php Lists all the names in the database with add, edit and delete links
add.html A page with form to add data to the database
addaction.php Action page for the above form
edit.php A page with form to edit a row of data in the database
editaction.php Action page for the above form
delete.php A page which deletes a given row of data

Finally our file system will look like below:

- index.php
- add.html
- addaction.php
- edit.php
- editaction.php
- delete.php

classes (class files folder)
     - dbConnect.php
     - addClass.php
     - editClass.php
     - selectClass.php
     - selectAllClass.php
     - deleteClass.php

 

Data Flow

Now let us look at how a row of data is created in the database.


User submitts data through the form in the file add.html

File: add.html

Code: <form name="form" method="post" action="addaction.php">

After user clicks on the submit button, addaction.php file is processed. Since, the method defined is post, user submitted data will be available through $_POST array in addaction.php file. 

Control is passed to addaction.php file.


File: addaction.php

Code: require_once('classes/addClass.php');

Content of the file addClass.php is read.


File: addClass.php

Code: require_once('dbConnect.php');

Content of the file dbConnect.php  is read. (No object has been created upto this point.)

Control moves to next line in the file addClass.php as shown below.


File: addClass.php

Code: class addClass extends dbConnect{}

After code from dbConnect.php is included in addClass.php, the class addClass is extended from the class dbConnect of dbConnect.php.

When a class extends another class, it is able to access all the variables and functions of the later class.

Since, addClass extends dbConnect, addClass has access to all the variables and functions of class dbConnect from dbConnect.php. This will come handy later on.


File: addaction.php

Code: $name=$_POST['name'];

Value submitted by the user is pulled from the associative array $_POST using "name" as the key. This comes from two parameters of the form in add.html:

  • method type
  • name of intput textfield

In our case, post is the method type and name is the name of the input textfield in the form at add.html. If the name of the input textfield was staffname, we would be pulling this content from $_POST['staffname']


File: addaction.php

Code: $add=new addClass();

Object of class addClass is created. This is where the magic of OOP happens.

dbConnect class has the following function defined in it:

function __construct() { }

This function is called constructor function. If a class A contains such function, it  is automatically called when the object of the class A is created. If another class B extends this class A and if the class B doesnt have its own constructor fuction, the function is called even when the object of class B is created.

Since, class addClass extends class dbConnect,  and since addClass doesnt have its own constructor function, thus when object of class addClass is created, the parent class's constructor function is automatically called.

Link: Constructor function basics

Now the control moves to this function in the file dbConnect.php.


File: dbConnect.php

Code:

function __construct(){

$this->con=new mysqli($this->host,$this->username,$this->password,$this->db);

...

}

mysqli is readymade class which has all the database connection variables. It also has a function called query which takes a sql query as an argument. 

$this->con refers to the $con variable of the current class, dbConfig. It is set as an object of the mysqli class. Database connection is attempted at the time of this object creation by passing all the necessary arguments.

Code:

if ($this->con->connect_error){

echo 'Something is wrong';

}

$this->con->connect_error refers to a connection variable, $connect_error of the mysqli class's object, $this->con. In case of database connection failure, this variable is set. This feature can be used to test the database connection.


So far, database connection has been established. Control moves to next line of code in addaction.php

File: addaction.php

Code: $add->addFunction($name);

This passes the user submitted value, $name to the function addFunction of the class addClass in addClass.php


File: addClass.php

Code: 

public function addFunction($name) {

$query="insert into oop_table values ('','".$name."')";

$result=$this->con->query($query);

Rembmer $con variable from dbConnect.php which was set was as object of mysqli class ? As mentioned before, this class has a function called query() which takes sql query as an argument.

Please note that nesting of similar kind of quotes does not work. That means, dont use pair of double quotes inside another pair of double quotes and likewise for single quotes.

For example:

$query="insert into oop_table values ("","apple")";

When you do this, the first of the inside pair will close the first of the outside pair double quotes. So the quotes will actually pair as follows:

"insert into oop_table values ("     ","    apple      ")";

Hence, use pair of single quotes inside pair of double quotes or vice versa. Such as follows:

$query="insert into oop_table values ('','apple')";

Code: 

If($result){

header('Location:index.php');

}

In case the query is successful, user is redirected to the index.php.