Learn PHP,HTML,CSS,Javascript,MySQL,Jquery

Friday, 9 August 2019

PHP OOP CRUD Tutorial - PHP Object Oriented Prograaming - Step By Step

PHP OOP CRUD Tutorial Step By Step

Creating PHP CRUD using oop structure is the best practice of programming. CRUD stands for Create, Read, Update, Delete. Create means inserting data into database using INSERT query, Read means selecting data from database using mysqli SELECT query, Update means editing data using mysqli UPDATE query, Delete means deleting data using DELETE query.


When we develop a web application, we need to use CRUD operation in most of the time. OOP stands for Object Oriented Programming. In OOP coding structure classes and functions are used to build the application. Web developers use OOP coding structure to create a well organized and structred form of coding.
In this article we will learn about how to create PHP CRUD using oop concepts. We will use mysqli to communicate with the PHPMyAdmin database.
As a web developer writing code using OOP is the best practices of programming.
Your Feedback is very imortant for us. If there is something in this article that confusing you or hard to understand then give us your feedback through leaving a comment below. Write your feedback in detailed description and we will respond to you and we will give it much importance. Thanks!

Overview of PHP CRUD Using OOP

In this topic we are going to create a CRUD application in PHP using OOP. In this example I have used a person_detail table to implement a CRUD operation in PHP using OOP.
Following steps are used to implement CRUD operation in PHP using OOP.
We will create only three files index.php, config.php and action-crud.php to manage all the CRUD functinality code.
  • Create a person_detail table in database.
  • Create a config.php file - for database connection.
  • Create an index.php file - for CRUD client side functinality.
  • Create action-crud.php - for PHP class and functions
  • Create - (insert query)
  • Read - (select query)
  • Update - (update query)
  • Delete - (delete query)

In this CRUD web application, I have used only one web page to implement CRUD operation using OOP. We can also use separate pages for Create, Read,Update and Delete. In many situations we need to implement the CRUD operation on a single page. But if you want to implement CRUD operation on separate pages then you can create it very easily after reading and practice of this tutorial.

1- Creating a Database Table

CREATE TABLE `person_detail` ( `id` int(11) NOT NULL, `firstname` varchar(100) NOT NULL, `lastname` varchar(100) NOT NULL, `email` varchar(150) NOT NULL, `phone` varchar(50) NOT NULL, `address` varchar(255) NOT NULL, `postal_code` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `person_detail` ADD PRIMARY KEY (`id`); ALTER TABLE `person_detail` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

2- Create config.php

In config.php file we will create a class with class name DB and create a function connect_db() within DB class. For connecting with database we will create a function connect_db() and when we want to connect with database we will call this function.
After closing DB class, create a base url within config.php file outside of the DB class and initialize this base url variable basic path of your project.
Here is the code to implement DB class,a function connect_db() to connect with database and base url variable initialization.
class DB { public function connect_db(){ $connection = mysqli_connect('localhost', 'root', '', 'test'); if(mysqli_connect_error()){ die("Database Connection Failed" . mysqli_connect_error() . mysqli_connect_errno()); } else { return $connection; } } } $base_url="http://localhost/crud"; After including this config.php file into other PHP files we can connect to database using this config file like action-crud.php. In the base_url variable crud is the folder name and all our files included within this folder. In other words this is our working directory.

3- Create index.php HTML Form and Table

In this index.php we are going to write HTML form code using Bulma css framework for styling and designing HTML form. We will create some input fileds to insert data into database table person_detail and after Create(insert query) execution we will also use this same form for Update(update query) operation.
This form contains 6 input fields for first name, last name, email, phone, address, postal code. In the header tags of HTML We will link Bulma css files from our working directory folder crud.
<html> <head> <title>Create</title> <link href="&lt;?php echo $base_url; ?&gt;/style/bulma-0.7.4/css/bulma.min.css" rel="stylesheet" type="text/css"></link> <link href="&lt;?php echo $base_url; ?&gt;/style/bulma-0.7.4/css/bulma.css" rel="stylesheet" type="text/css"></link> </head> <body bgcolor="lightblue"> <section class="body is-fullheight"> <div class="hero-body"> <div class="container has-text-centered"> <div class="columns is-multiline"> <div class="column is-8 is-offset-2"> <form action="index.php" method="post"> <div class="box"> <h1 class="title"> Save Person Detail</h1> <input name="txthideid" type="hidden" value="&lt;?php echo $id;?&gt;" /> <div class="field is-horizontal"> <div class="field-body"> <div class="field"> <div class="control"> <label class="label">First Name</label> <input class="input is-info" name="txtfname" type="text" value="&lt;?php echo $fname;?&gt;" /> </div> </div> <div class="field"> <div class="control"> <label class="label">Last Name</label> <input class="input is-info" name="txtlname" type="text" value="&lt;?php echo $lname;?&gt;" /> </div> </div> </div> </div> <div class="field is-horizontal"> <div class="field-body"> <div class="field"> <div class="control"> <label class="label">Email Address</label> <input class="input is-info" name="txtemail" type="text" value="&lt;?php echo $email;?&gt;" /> </div> </div> <div class="field"> <div class="control"> <label class="label">Home Address</label> <input class="input is-info" name="txtaddress" type="text" value="&lt;?php echo $address;?&gt;" /> </div> </div> </div> </div> <div class="field is-horizontal"> <div class="field-body"> <div class="field"> <div class="control"> <label class="label">Phone Number</label> <input class="input is-info" name="txtphone" type="text" value="&lt;?php echo $phone;?&gt;" /> </div> </div> <div class="field"> <div class="control"> <label class="label">Postal Code</label> <input class="input is-info" name="txtpostal" type="text" value="&lt;?php echo $postal;?&gt;" /> </div> </div> </div> </div> <div class="field is-horizontal"> <div class="field-body"> <div class="field"> <div class="control"> </div> </div> <div class="field"> <div class="control"> <input class="button is-info is-large" name="btnsubmit" type="submit" value="Save" /> </div> </div> </div> </div> </div> </form> </div> <div class="column is-2"> </div> </div> </div> </div> </section> </body> </html>

How to Fecth Data from Database and Display in Textbox Using PHP ?

How to Set Value in Textbox Using PHP?

Here I will give answer of these two but similar questions.
In above HTML form you can see above I have included an action-crud.php file which contains config.php and all other functionality to implement CRUD operation using OOP structure. In the value property of each textbox, I have passed the PHP variable. These variables are declared in action-crud.php file.
There are two reasons of using PHP variables in value property of HTML input fields. First is when we click on Save button after click event of button data will be repopulated to the input fields either successfully saved data or not. Second reason is that when we click on a row of html table to update data of HTML table row its data will be passed to relevant input field.

4- Create action-crud.php

In this file first include the config.php file then create a class with the name of crud and outside of this class create an object of crud class. After creating the class include this action-crud.php file into index.php file.
Here is the code of crud class.
include ('config.php'); class crud extends DB { } $object=new crud(); $output=''; $fname=''; $lname=''; $email=''; $phone=''; $address=''; $postal=''; $id=''; This class is extending DB class which we have created within config.php file. By extending the class DB we can use all functions of DB class into this crud class. We are extending this DB class to connect with mysql database. In this class we will create functions for implementing CRUD operation. Outside of this class create an object of the class. After creating an object of class declare PHP varibales which we have passed into value property of input fileds in index.php file.

5- Insert Data into Database (Create)

Now we will craete a function name as create in our crud class. We will pass 6 parameters to this create function for inserting HTML form input fields data into database. We will pass these parameters into VALUES() of insert query.
First of all create a varibale and initialize this varibale with insert query and pass all 6 paramters into this insert query. After writing insert query, now we need to execute this query using mysqli_query() function of PHP and pass two paramters into this function first paramter is the connection to database and second is the insert query variable.
For example, mysqli_connect($this-connect_db(),$sql) or mysqli_connect($conn,$query). We will use mysqli_connect($this-connect_db(),$sql), in first parameter we are caaling a function connect_db() from another class DB and second paramter is for insert query.
Here is the code to insert data into database.
Note : Write this code into action-crud.php file. Write create function within the crud class and other code below the class object and varibales.
public function create ($fname,$lname,$email,$phone,$address,$postal) { $sql="INSERT INTO `person_detail`( `firstname`, `lastname`, `email`, `phone`, `address`, `postal_code`) VALUES ('$fname','$lname','$email','$phone','$address','$postal')"; $query=mysqli_query($this-&gt;connect_db(),$sql); if($query) { return true; } else { return false; } } //below is the code for save button click event and to implement insert query if(isset($_POST['btnsubmit'])) { $fname=$_POST['txtfname']; $lname=$_POST['txtlname']; $email=$_POST['txtemail']; $phone=$_POST['txtphone']; $address=$_POST['txtaddress']; $postal=$_POST['txtpostal']; $id=$_POST['txthideid']; if($id =='') { $res=$object-&gt;create($fname,$lname,$email,$phone,$address,$postal); if($res) { $output="Successfully Saved"; } else { $output="Failed to Save"; } } } I have explainded above create function. Now I will explain about save button click event. We have used an if statment, isset() function of PHP and $_POST['btnsubmit'] btnsubmit is the name of button save.
Within this if statment assign HTML form input fields names to PHP varibales. While assigning these values use mysqli_real_escape_string() function to strip data from input fields.
Here it the answer of one more question. How to Prevent SQL Injection in PHP? If you want to use this mysqli_real_escape_string write the below sanitize function into crud class to sanitize user submitted data and return the sanitzed data. After wring this function into crud class you can assign input fields values to variables like this : $fname=$object->sanitize($_POST['txtfname']). This way you can save your data from sql injection.
public function sanitize($var){ $value = mysqli_real_escape_string($this-connect_db(), $var); return $value; } after assinging input fields data to varibales check if id is empty then call the create function to insert data into database and pass all above varibales into create function. Here id is used for hidden field which we will use later for update.

6- Read Data from Database and Display in index.php

I am using only one HTML page for complete CRUD operation implementation using OOP structure. So for second letter of CRUD R , I am going to display data from the database into html table. We will write a read function and in this function use a select query of mysql to fetch data from the database table person_detail.
Simply create a read function within the crud class, then call this function and assign to a variable within html table of index.php file. After calling this function create a while loop and assign function varibale into another varibale within while loop. We will mysqli_fetch_array() function within while loop to fetch data from the function in an array format.
Here is the code to read data from the database.How to Display Data From Database into HTML Table Using PHP?
Note : Add read function within crud class and html table within index.php.
public function read() { $sql="select * from person_detail"; $query=mysqli_query($this-&gt;connect_db(),$sql); return $query; } //add this html table code below the html form in index.php file <div class="column is-8 is-offset-2"> <--php $res=$object->read(); while($row=mysqli_fetch_array($res)) { ?&gt; <br /> <table class="table is-bordered is-stripped is-narrow is-fullheight"> <thead> <tr> <th>ID</th> <th>Full Name</th> <th>Email</th> <th>Phone #</th> <th>Address</th> <th>Postal Code</th> <th>Update</th> <th>Delete</th> </tr> </thead><tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td><a class="button is-info" href="https://www.blogger.com/index.php?id=%3C?php%20echo%20$row[%27id%27];?%3E">Edit</a></td> <td><a class="button is-danger" href="https://www.blogger.com/index.php?trash_id=%3C?php%20echo%20$row[%27id%27];?%3E">Delete</a></td> </tr> </tbody> </table>

In above html table two additional columns are for update and delete operations which we are going to discuss next. Within this while loop start table body and table row tags. Now create tds and within these td tags we are printing the database values relevant to there column names.
On the right side of this html table we are using update and delete links. Within these anchor tags use an index.php with query string paramters id for update, trash_id for delete and pass the database table column id into these links.


7- Create UPDATE Operation

To execute this update operation first of all we need to display data of unique row of html table based on id into input fields of html form. Then we can update the data and submit the form and data will be updated based on id of that row.
We will use two functions one for reading data from the database according to the row id and other function for updating the data of the row based on its id. When someone click on edit link of html table row we will fetch the data from the database based on the row id.
Here is the code for updating data.
Note : Add below function within crud class and other code below the class after class object.
public function fetch_person_detail($id) { $sql="select * from person_detail where id=$id"; $query=mysqli_query($this-&gt;connect_db(),$sql); return $query; } //call fetch_person_detail function and pass data into varibales. if(isset($_GET['id']) &amp;&amp; $_GET['id'] !=='') { $id=$_GET['id']; $fetch_data=$object-&gt;fetch_person_detail($id); while($row=mysqli_fetch_array($fetch_data)) { $fname=$row['firstname']; $lname=$row['lastname']; $email=$row['email']; $phone=$row['phone']; $address=$row['address']; $postal=$row['postal_code']; } } When we write the above code, we will get data into input fields. Here $_GET['id'] is the URL paramter to get value of id. fetch_person_detail function is used for fetching data from the database of a unique row where id is equal to url value.
Now create a second function to update the data when the html form will be submitted on save button click. Becuase we are using only one page to implement CRUD operation using OOP, so I will call the Update(update query) function within save button click event code in action-crud.php file.
Previously we have called the create(insert query) function within $_POST['btnsubmit'] and used the if id is equal to empty. Now we will call the update function within else part of button click event. If id not equal to empty run the update query.
Here is the code to implement update query.
Note : Add below function within crud class and below this update_person_detail function is the complete code of save button replace above save button code with this code.
public function update_person_detail($fname,$lname,$email,$phone,$address,$postal,$id) { $sql="UPDATE `person_detail` SET `firstname`='$fname',`lastname`='$lname',`email`='$email',`phone`='$phone',`address`='$address',`postal_code`='$postal' WHERE id='$id'"; $query=mysqli_query($this-&gt;connect_db(),$sql) or die(mysqli_error($this-&gt;connect_db())); return $query; } //below is the complete code of save button replace above save button code with this code. if(isset($_POST['btnsubmit'])) { $fname=$_POST['txtfname']; $lname=$_POST['txtlname']; $email=$_POST['txtemail']; $phone=$_POST['txtphone']; $address=$_POST['txtaddress']; $postal=$_POST['txtpostal']; $id=$_POST['txthideid']; if($id =='') { $res=$object-&gt;create($fname,$lname,$email,$phone,$address,$postal); if($res) { $output="Successfully Saved"; } else { $output="Failed to Save"; } } else if($id !=='') { $res=$object-&gt;update_person_detail($fname,$lname,$email,$phone,$address,$postal,$id); if($res) { $output="Successfully Updated"; } else { $output="Failed to Update"; } } }

8- Delete Records

when user click on delete link of html table row the id of that row will be passed to url paramter. On the other side this id will be used within delete_person_detail function to delete the data based on the id.
We will use a function delete_person_detail within crud class for writing delete query. After creating the delete function, we will call this function below the object of class within if statment. After deleting record redirect to index.php page.
Here is the code to delete record. Note: Add the delete_person_detail() function within crud class and if statement outside of the class.
public function delete_person_record($id) { $sql="delete from person_detail where id=$id"; $query=mysqli_query($this-&gt;connect_db(),$sql); return $query; } if(isset($_GET['trash_id']) &amp;&amp; $_GET['trash_id'] !=='') { $id=$_GET['trash_id']; $delete=$object-&gt;delete_person_record($id); header('location:'.$base_url.'/index.php'); } Now we have successfully created the CRUD application using OOP structre in PHP. If you have any issue let me know through comment below.

Download the Complete Source Code

If you have any problem with the above source code, you can download this complete source code. Download Source Code

No comments:

Post a Comment