Simple CRUD operations in PHP using MYSQL – [Procedural]

In this tutorial we will see how to create simple CRUD operations in PHP using MYSQL. I will use procedural mysqli functions to create, read, update and delete. The reason of using procedural mysqli functions is to give PHP beginners a quick overview of how crud operation works in PHP. I will try my best to explain all the aspects of this topic in very simple way. So let’s start with very basic.

PHP CRUD Operations:

CRUD is an acronym of Create, Read, Update, and Delete. PHP provides a set of functions for each database which php supports. I will be using MYSQL database and PHP has different set of functions to achieve crud operations in mysql. In short we will be doing following things.

  • Create: Create a new record in mysql database
  • Read: Read record(s) from mysql database
  • Update: Update single record in mysql database
  • Delete: Delete single record in mysql database

PHP functions for MYSQL:

Following are the PHP functions we will be using to achieve our goal.

  • mysqli_connect(host, dbuser,dbpass,database): is used to connect to database
  • mysqli_query(db_connection, sql_query): is used to run query
  • mysqli_affected_rows(db_connection): returns the number of affected rows from previous SQL statement
  • mysqli_insert_id(db_connection): returns the auto generated id from last query
  • mysqli_error(): returns the description of the last error

PHP CRUD Example:

Now let’s jump into the coding part. I am going to use blog example in which I will be creating following PHP files and folder.

  • Config.php: This file has a Database Connection
  • Create.php: This file will use to save new blog
  • Edit.php: This file will use to edit blog
  • Index.php: This file will use to display all blogs. And this file will also have delete blog code.
  • Css: This folder has style.css file

PHP CRUD Example Source Code

Create Database:

First of all lets create a database;

Create Database Table:

Now create blog table. You can copy paste below code to your phpmyadmin or any sql client.

Insert Records in Database:

Let’s add some dummy blogs.

Database Connection File (config.php):

Create Blog (create.php):

Read Records (index.php):

Edit Blog (edit.php):

Delete records (index.php):

 

Posted in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *