Validate an array input field

This tutorial is based on procedural PHP. It will teach you how to validate an array input field with a specific field. We find it really hard to validate an array input field. So this tutorial is make the concept more clear. The source code for this tutorial is available at end of the tutorial.

Step 1: Setup the working environment

Go to the htdocs and create a folder named validate_array_input and create a file index.php. Paste or write this code into the index.php


<!DOCTYPE html>
<html>
<head>
	<title>Validate the array input field form</title>
</head>
<body>

<form action="" method="post">
	
	<?php for ($i=1; $i < 4; $i++) { ?>		
		<div style="margin-bottom: 20px;">
			<label>Product <?php echo $i; ?>: </label>							
		
			<input type="text" name="productName[<?php echo $i; ?>]" value="<?php echo $_POST['productName'][$i]; ?>"/> 
		</div>
	<?php } // /.foreach ?>

	<input type="submit" name="submitForm" value="Submit" />
</form>

</body>
</html>

As you can we can see we have created three input fields by iterating 3 times. So this means we will have three input filed.


<?php 
for ($i=1; $i < 4; $i++) { 
} 
?>

This means it will iterate 3 times, and the $i variable will repeat until its value is less than 4.


    <input type="text" name="productName[<?php echo $i; ?>]" value="<?php echo $_POST['productName'][$i]; ?>"/> 

Now this input field is inside the iteration. This means the input field is repeated three times with the array number 1, 2, and 3. This will represent as productName[1], productName[2], productName[3]. The same logic goes to the value attribute of the input element.

If you have followed these steps correctly then the output of the code will look like the below image:

Step 2: Work with PHP validation

We are almost finished with this tutorial, now we will add these codes as shown below.


<?php 
$errors = array();
if(isset($_POST['submitForm'])) {

	$productName = $_POST['productName'];

	foreach ($productName as $key => $value) {		
		if(empty($productName[$key])) {
			$errors[$key] = "<p style='color:red;'> Product ".$key." Field is Required</p> ";
		}
	} // /foreach

	if(empty($errors)) {
		// validation is ok, and here we can insert the data into the database
	}

}
?>

Add these codes right above the HTML tag. This code checks if the form is submitted. If yes first it stores the array data in the $productName variable. After that, it iterates through each array and checks if the value is empty or not. If it's empty then it stores the error message into any error with the $key variable which counts the array key number.

Another if statement checks if the $errors variable is empty. If the $errors are empty then the validation is validated.


 <?php 
	if(!empty($errors)) {
		foreach ($errors as $key => $value) {
			if($key == $i) {
				echo $value;
			} // .if
		} // /.foreach errors
	} // /.if
?>

This code will be right below the input field to display the validation errors. The first if statement checks if the $errors variable is not empty and if not empty then it iterates that variable to display each message. As you know $i variable is from for loop. Now it checks if the $key and $i variable match with each other

Integrate the step 2

By integrating the step 2 code it should look like the below code


 <?php 

	$errors = array();
	if(isset($_POST['submitForm'])) {

		$productName = $_POST['productName'];

		foreach ($productName as $key => $value) {		
			if(empty($productName[$key])) {
				$errors[$key] = "<p style='color:red;'> Product ".$key." Field is Required</p> ";
			}
		} // /foreach

		if(empty($errors)) {
			// validation is ok, and here we can insert the data into the database
		}

	}

	?>

	<!DOCTYPE html>
	<html>
	<head>
		<title>Validate the array input field form</title>
	</head>
	<body>

	<form action="" method="post">
		
		<?php for ($i=1; $i < 4; $i++) { ?>		
			<div style="margin-bottom: 20px;">
				<label>Product <?php echo $i; ?>: </label>							
			
				<input type="text" name="productName[<?php echo $i; ?>]" value="<?php echo $_POST['productName'][$i]; ?>"/> 
				<?php 
					if(!empty($errors)) {
						foreach ($errors as $key => $value) {
							if($key == $i) {
								echo $value;
							} // .if
						} // /.foreach errors
					} // /.if
				?>		
			</div>
		<?php } // /.foreach ?>

		<input type="submit" name="submitForm" value="Submit" />
	</form>

	</body>
	</html>

I hope this helps you a lot.

For Source Code:

Download

Parking Management System – Codeigniter

The parking Management System is the most complete and versatile parking management system. This system is an open-source project. We have provided the most advanced backend management functionality with parking slots, parking rates, parking categories, and more of the best functionality.

Parking Management System is an open-source project for people who wants to grab the core idea of the data process within the system. This system is built on CodeIgniter – PHP framework, adminlte, bootstrap, javascript, jQuery, and Ajax. This system, Parking Management System, is based on the Web Application. It provides advanced functionality and runs daily basic requirements for the parking system. Many users can manage work with the system based on their user permission.

The admin can create as many users as he wants based on the user’s permission. The permission is set up in the group section. The super admin can create the group with limited functionality. Please have a look at the video which will make
the concept more clear to you.

In this application, there are a lot of dependencies that you will have to understand. For instance, to create the parking information, you must have the parking category, rates, and slot information on the system. Without them the parking information is incomplete.

Please follow each and every step to run this system on your system. You will need to make a few changes to the code to run this application our your design. I hope you have installed XAMPP (windows), and MAMP (MACOS) on your system.

The source code and the database are provided at the end of the tutorial. Please download them and follow each and every step to successfully install and run the system.

Users

  • Admin

Features

  • Manage User

    • Add new user detail
    • View, Update, and remove user information
  • Manage Groups

    • Add new group information
    • View, Update, and remove group information
  • Manage Category

    • Add category information
    • View, Update, and remove category information
  • Manage Rates

    • Add rate information
    • View, Update, and remove rate information
  • Manage Slot

    • Add slot information
    • View, Update, and remove slot information
  • Manage Parking

    • Add parking information
    • View, Update, and remove parking information
    • Update the slot availability
  • Reports

    • View the paid parking information based on the yearly
  • Manage Company information

    • Update the company information
  • View Profile information

    • View user profile information
  • Manage Setting

    • Update user information
    • Update password information

Requirements

  • PHP Version +7.0.0
  • Web Server ( Recommended: Apache with PHP and Mysqli )

Installing source code and database guidelines

Step 1: Download the database and source.

Step 2: Change port no.

Go to the application > config > config.php as shown below.

config

After that go to base_url, and update or remove the port no based on your system configuration:

[css autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” highlight=”” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”true” title=””]
$config[‘base_url’] = ‘http://localhost:8888/parking’;
[/css]

Step 3: Create the database and import the SQL

Go to http://localhost:8888/phpmyadmin, and click on the database section. There create the database name as “parking”.

After that click on the created database and import the database file which has been provided.

Now, Go to the application > config > Database.php file.

folder_structur

In this file there are 3 things to update. They are username, password, and database.

username: Change username based on database user’s username
password: Change password based on database user’s password
database: Change database name if you different database name


$db['default'] = array(
   'dsn'	=> '',
   'hostname' => 'localhost',
   'username' => 'root',
   'password' => 'root',
   'database' => 'parking',
   'dbdriver' => 'mysqli',
   'dbprefix' => '',
   'pconnect' => FALSE,
   'db_debug' => (ENVIRONMENT !== 'production'),
   'cache_on' => FALSE,
   'cachedir' => '',
   'char_set' => 'utf8',
   'dbcollat' => 'utf8_general_ci',
   'swap_pre' => '',
   'encrypt' => FALSE,
   'compress' => FALSE,
   'stricton' => FALSE,
   'failover' => array(),
   'save_queries' => TRUE
);

If this project really helped you guys, then please comment, and share. Thank you.

CHANGELOG

1.1>
* Fixed the session issue
* Fixed the empty string core/Output.php
* Fixed the setCookie() deprecated issue.

System Live Preview

Live Preview

For Source Code:

Download

Online School Management System

School Management System, is an open-source project for people who wants to grab the core idea of the data process within the system. As well as you can practice this system for the assignments too. Though, if you want to use it on the online project then I highly recommend implementing PHP security. Since we just wanted to provide this system as a platform for beginners or intermediate programmers to study and learn how the data process from the frontend to the backend in the system.

This system is built with CodeIgniter – PHP framework, bootstrap, and jquery. This system, School Management System, is based on the Web Application. It provides advanced functionality to run the daily basic requirement for the school program. The system can be manipulated by one user as an admin.

In this application, there are some dependencies you will need to understand. For example, you want to add a section for a class. Without class information, the section information cannot be added to the system. Similarly, these concepts apply to the subject, student, etc. Without any class and section, the subject, and student information cannot be created by the system.

Please read the below instruction to run the application on your system without any difficulties. There are a few changes required in the source code to run the application. So please follow the steps carefully.

Users

  • Admin
  • Username: admin
  • password: password

Features

  • Manage Class

    • Add class information
    • View, Update, and remove class information
  • Manage Section

    • Add section information
    • View, Update, and remove section information
  • Manage Subject

    • Add section information
    • View, Update, and remove section information
  • Manage Student

    • Add a single student information
    • Add bulk student information
    • View, Update, and remove student information
  • Manage Teachers

    • Add teacher information
    • View, Update, and remove teacher information
  • Manage Attendance

    • Add Teacher and Student attendance information
    • View, Update and Remove teacher and student attendance information
  • Manage Marksheet

    • Add, View, Update, and Remove mark sheet name information
    • Add, View, Update, and Remove student-obtained marks into the marksheet
  • Manage Accounting

    • Add Student Payment Information
    • View, Update, and Remove student payment information
    • Add, View, Update, and Remove expenses information
    • View Income information
  • Change Password
  • Change Username

Requirements

  • PHP Version +5.4.4
  • Web Server ( Recommended: Apache with PHP and Mysqli )

Changing Port No

No need to worry. This is just a small task. All you need to do is:
Step 1: Go to the application > config > config.php as shown below.
config

After that go to base_url, and change or delete the port no as shown below code:


$config['base_url'] = 'http://localhost:9080/sms/index.php/';

Download School Management System

Please Read:

To run this system, you need to create a database in phpMyAdmin. Either you can create a database namely sms or something else. If you have a database name or something else then, you have to change it in the source code. To change the database name in the source code.

Step 1: Go to the application > config > Database.php file.
folder_structur

Step 2: You will see the database name in the $db array. Change the name of the database to whatever you desired. As shown below:


$db['default'] = array(
   'dsn'	=> '',
   'hostname' => 'localhost',
   'username' => 'root',
   'password' => '',
   'database' => 'sms',
   'dbdriver' => 'mysqli',
   'dbprefix' => '',
   'pconnect' => FALSE,
   'db_debug' => (ENVIRONMENT !== 'production'),
   'cache_on' => FALSE,
   'cachedir' => '',
   'char_set' => 'utf8',
   'dbcollat' => 'utf8_general_ci',
   'swap_pre' => '',
   'encrypt' => FALSE,
   'compress' => FALSE,
   'stricton' => FALSE,
   'failover' => array(),
   'save_queries' => TRUE
);

CHANGELOG

1.1>
* Fixed the session issue
* Fixed the empty string core/Output.php
* Fixed the setCookie() deprecated issue.

System Live Preview

Live Preview

For Source Code:
Download

If this project really helped you guys, then please comment, and share. Thank you.

How to upload image with ajax and php

AJAX (Asynchronous JavaScript and XML) is a popular technique to update part of a web page without reloading the whole page. The Ajax method will enhance the web application better, faster, and more interactive.

To upload the image into the database, we will be working with procedural PHP, and using the Ajax functionality to send the request to the server.

At the end of this tutorial, we have provided a source code and database link below section.

Table of Content

  1. Setting up assets file and project folder
  2. Configure the Database
  3. Creating a form
  4. Creating the PHP file to process
  5. Submitting the form using Ajax
  6. Display all uploaded data

1. Setting up assets file and project folder

The asset file that we will be working with in this tutorial is jquery, bootstrap, and fileinput. To download these files click on the asset name which will redirect to their official website.

Firstly, create the project folder named as upload_image or something else you desire. Secondly, after creating the project folder, go inside that project folder and create three folders (assets, php_action, uploads) i.e. [upload_image/assets], [upload_image/php_action] and [upload_image/uploads], and two php files namely i.e. [upload_image/index.php] and [upload_image/view.php].

In the assets folder, create the three folders namely bootstrap, jquery, and file input, and paste those downloaded plugins respectively. In the php_action folder create a php file and name the file an uploadImage.php which will be processing the image information into the database. The uploads folder contains the uploaded images.

If you have followed the instruction correctly then the project folder and file structure could look like the below:

Upload Image Folder and file structure

2. Configure the Database

Database Name: upload_image
Table Name: users
Table Column: id, name, image

Copy and paste the following SQL command into your MySQL database to create a database and table.


CREATE DATABASE `upload_image`;

CREATE TABLE `upload_image`.`users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `image` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

 

3. Creating a form

We will be using the Bootstrap framework to create a simple form for better UI. For now, go to the index.php file and paste these codes and we will go through them afterward.


<!DOCTYPE html>
<html>
<head>
	<title></title>
	<!-- boostrap css-->
	<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.min.css">

	<!-- file input css -->
	<link rel="stylesheet" type="text/css" href="assets/fileinput/css/fileinput.min.css">
</head>
<body>

	<div class="col-md-5 col-sm-5 col-md-offset-4 col-sm-offset-4">
		<div class="page-header">
			<h3>Upload Image with Ajax</h3>

			<a href="view.php" class="btn btn-default">View User</a>
		</div>

		<div id="messages"></div>

		<form action="php_action/uploadImage.php" method="post" enctype="multipart/form-data" id="uploadImageForm">
		  <div class="form-group">
		    <label for="fullName">Name</label>
		    <input type="text" class="form-control" id="fullName" name="fullName" placeholder="Name">
		  </div>
		  <div class="form-group">
		    <label for="exampleInputPassword1">Photo</label>		    
		    <div id="kv-avatar-errors-2" class="center-block" style="width:800px;display:none"></div>

            <div class="kv-avatar center-block" style="width:200px">
		        <input id="avatar-2" name="userImage" type="file" class="file-loading">
		    </div>
		  </div>
		  <button type="submit" class="btn btn-default">Submit</button>
		</form>

	</div>
	
	<!-- jquery -->
	<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
	<!-- bootsrap js -->
	<script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js"></script>
	<!-- file input -->
	<script src="assets/fileinput/js/plugins/canvas-to-blob.min.js" type="text/javascript"></script>	
	<script src="assets/fileinput/js/plugins/sortable.min.js" type="text/javascript"></script>	
	<script src="assets/fileinput/js/plugins/purify.min.js" type="text/javascript"></script>
	<script src="assets/fileinput/js/fileinput.min.js"></script>

	<script type="text/javascript">
		var btnCust = '<button type="button" class="btn btn-default" title="Add picture tags" ' + 
		    'onclick="alert(\'Call your custom code here.\')">' +
	    	'<i class="glyphicon glyphicon-tag"></i>' +
		    '</button>'; 
		    
		$("#avatar-2").fileinput({
	    overwriteInitial: true,
	    maxFileSize: 1500,
	    showClose: false,
	    showCaption: false,
	    showBrowse: false,
	    browseOnZoneClick: true,
	    removeLabel: '',
	    removeIcon: '<i class="glyphicon glyphicon-remove"></i>',
	    removeTitle: 'Cancel or reset changes',
	    elErrorContainer: '#kv-avatar-errors-2',
	    msgErrorClass: 'alert alert-block alert-danger',
	    defaultPreviewContent: '<img src="uploads/default-avatar.jpg" alt="Your Avatar" style="width:160px"><h6 class="text-muted">Click to select</h6>',
	    layoutTemplates: {main2: '{preview} ' +  btnCust + ' {remove} {browse}'},
	    allowedFileExtensions: ["jpg", "png", "gif"]
		});
	</script>
</body>
</html>

In this file, we will be including the downloaded plugins and create the form to upload the images. In the above code at the head section, we will be including the bootstrap and fileinput css file. At the bottom of the body section, we will be including the jquery, bootstrap, and fileinput js files.

4. Creating the PHP file to Process

In this section, we will be creating a simple PHP script to store the uploaded image file in the server directory by giving a unique name and storing that name in the database. For now, copy and paste these codes into the uploadImage.php file which is located in the php_action folder i.e. [upload_image/php_ation/uploadImage.php].


<?php 

if($_POST) {
	// database connection
	$server = '127.0.0.1';
	$username = 'root';
	$password = '';
	$dbname = 'upload_image';

	$conn = new mysqli($server, $username, $password, $dbname);

	// check db connection
	if($conn->connect_error) {
		die("Connection Failed : " . $conn->connect_error);
	} 
	else {
		// echo "Successfully Connected";
	}

	$valid = array('success' => false, 'messages' => array());

	$name = $_POST['fullName'];

	$type = explode('.', $_FILES['userImage']['name']);
	$type = $type[count($type) - 1];
	$url = '../uploads/' . uniqid(rand()) . '.' . $type;

	if(in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) {
		if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
			if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {

				// insert into database
				$sql = "INSERT INTO users (name, image) VALUES ('$name', '$url')";

				if($conn->query($sql) === TRUE) {
					$valid['success'] = true;
					$valid['messages'] = "Successfully Uploaded";
				} 
				else {
					$valid['success'] = false;
					$valid['messages'] = "Error while uploading";
				}

				$conn->close();

			}
			else {
				$valid['success'] = false;
				$valid['messages'] = "Error while uploading";
			}
		}
	}

	echo json_encode($valid);

	// upload the file 
}

In the above codes, the first script checks if the form is submitted.  After that, the database connection is created and stored in the conn variable for further processing. Secondly, the uploaded image type is checked and creates a unique id for the image name and moves to the uploads folder, and stores the information in the database.

5. Submitting the form using Ajax

To upload the form using Ajax, we will need to do several things in the index.php file. Copy and paste these codes into the index.php file at the end of the script where avatar-2 is initiated.


<script>
   $(document).ready(function() {
      $("#uploadImageForm").unbind('submit').bind('submit', function() {

         var form = $(this);
         var formData = new FormData($(this)[0]);

         $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: formData,
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,
            async: false,
            success:function(response) {
               if(response.success == true) {
                  $("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                  '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                  response.messages + 
               '</div>');

                  $('input[type="text"]').val('');
                  $(".fileinput-remove-button").click();
               }
               else {
                  $("#messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                  '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                  response.messages + 
               '</div>');
               }
            }
         });

         return false;
      });
   });
</script>

In the above codes, the form on submit event is caught by #uploadImageForm id which was created in Chapter 3. The form variable holds the action, and method values of the form element, whereas the formData variable holds the data of the form. After that, the jquery built-in Ajax function will be used to process the data to the server and respond with the message state.

6. Display all uploaded data

In this section, we will be displaying the users’ information that is stored in the database. Copy and paste these codes into the view.php file which is located at [upload_image/view.php].


<!DOCTYPE html>
<html>
<head>
	<title></title>

	<!-- boostrap css-->
	<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.min.css">
</head>
<body>

<br /> <br /> <br />
<div class="col-md-5 col-sm-5 col-md-offset-4 col-sm-offset-4">
	<a href="index.php" class="btn btn-default">Back</a>
	<table class="table table-bordered">
		<tr>
			<th>S.no</th>
			<th>Name</th>
			<th>Photo</th>
		</tr>

		<?php 
		// database connection
		$server = '127.0.0.1';
		$username = 'root';
		$password = '';
		$dbname = 'upload_image';

		$conn = new mysqli($server, $username, $password, $dbname);

		// check db connection
		if($conn->connect_error) {
			die("Connection Failed : " . $conn->connect_error);
		} 
		else {
			// echo "Successfully Connected";
		}

		$sql = "SELECT * FROM users";
		$query = $conn->query($sql);

		$x = 1;
		while ($result = $query->fetch_assoc()) {
			$image = substr($result['image'], 3);

			echo "<tr>
				<td>".$x."</td>
				<td>".$result['name']."</td>
				<td> <img src='".$image."' style='height:100px; width:100px;' /> </td>
			</tr>";
			$x++;
		}

		?>
	</table>
</div>

</body>
</html>

Download Source Code

Download

CodeIgniter Tutorial – Register and Login with Ajax

Codeigniter is a PHP framework that contains libraries, helpers, plugin-in, and other resources. It will make the PHP codes simple, quick, and user-friendly. It is a lightweight MVC programming technique to keep the business logic separate from the layout of the application. MVC stands for Model View Controller which is a software development method splitting the data layer (Model), the business logic (Controller), and the layout of the application (View). With the help of this framework, we will be building the simple Register and Login application with Ajax.

Table of Content

  1. Introduction
  2. Configure Config File
  3. Configure Database
  4. Database Connection
  5. Register and Login Demonstration
  6. Source Code

Introduction

This tutorial will teach you to create a register and login system with Ajax. The registration and login system is the most important role in the web application. The user’s login status will be checked by the session.

The source code of this application is provided at the end of this tutorial, you can easily download them by clicking on the download button. As well as the database is also required to run the application correctly. So please do not forget to download the database and run them into the phpMyAdmin.

Configure Config File

In this part, Go to the config.php file i.e. application/config/config.php and you must change the base URL root to work the code properly without any errors. You will have to modify the base URL value in the config file to help the CodeIgniter to guess the protocol and path of your installation.


<?php
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
| http://localhost/codeigniter_register_login/
*/
$config['base_url'] = 'http://localhost:9080/codeigniter_register_login/';

?>

Configure Database

Database Name: codeigniter_register_login
Table Name: users
Table Column: id, username, password, salt, name, contact

To create the database for this tutorial, either you can download the SQL file which is provided at the end of this tutorial or copy and paste the following SQL command into your MYSQL Database.


CREATE DATABASE `crud_datatables_codeigniter`;

CREATE TABLE `codeigniter_register_login`.`users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `salt` text NOT NULL,
  `name` varchar(255) NOT NULL,
  `contact` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Database Connection

In database.php file i.e. [application/config/database.php], contains a database connection. If you have a different database name then change the database name in the database.php file highlighted below.


$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'codeigniter_register_login',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Source Code !!

Download

Simple CRUD with PHP, MYSQLI

CRUD (Create, Retrieve, Update, Delete) is a usual job in web development. In Later Career, as a web developer, you’ll encounter lots of CRUD functionality in your career. The design of a CRUD will allow the users to create/retrieve/update/remove the data from the front end of the system. Generally, with the help of PHP as a server-side programming language, the data will be stored in MYSQL Database. PHP as a server-side language will be manipulating MYSQL Database tables to perform a particular action triggered by the users.

Table of Content

  1. PHP CRUD Part 1 Introduction
  2. PHP CRUD Part 2 Configure Database
  3. PHP CRUD Part 3 Setting up project folder
  4. PHP CRUD Part 4 Database Connection
  5. PHP CRUD Part 5 Create
  6. PHP CRUD Part 6 Retrieve
  7. PHP CRUD Part 7 Update
  8. PHP CRUD Part 8 Remove

1. PHP CRUD Part 1 Introduction

In this section, the overall CRUD operation is introduced as well as we are going to develop a simple CRUD (Create, Retrieve, Update, Delete) PHP operation. In a web application, these are the basic stuff required to create, retrieve, update, and delete the data using PHP with MYSQL Database. You will be creating the database tables and inserting the data into the database tables without any fatal errors. This is an uncomplicated and easy tutorial to learn a CRUD operation. To understand how CRUD operations work, I recommend you go through each part of this tutorial.

The below video illustrates the final system of this tutorial. The source code of this application will be provided at the end of this tutorial.

2. PHP CRUD Part 2 Configure Database

Database Name : php_crud
Table Name : members
Table Column : id, fname, lname, contact, age, active

To create the database in this tutorial, there are two ways.

2.1 First way to create database

Copy and paste the following SQL command in your MySQL database to create a database and table



CREATE DATABASE `php_crud`; 

// create table
CREATE TABLE `php_crud`.`members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`contact` varchar(255) NOT NULL,
`age` varchar(255) NOT NULL,
`active` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;



2.2 Second way to create database

A tutorial video to demonstrate to you, how to create a database and tables for this tutorial

3. PHP CRUD Part 3 Setting up project folder

In this part, we will be creating a project folder and files for this tutorial. First of all, create the project folder as “crud_php”. After that create the create.php, edit.php, index.php, and remove.php files inside this project folder as shown [crud_php/create.php], [crud_php/edit.php] and so on.

Second, Create a folder named “php_action” inside this project folder as [crud_php/php_action] which will handle the server-side processing actions. In this directory create a create.php, db_connect.php, remove.php and update.php file as shown [crud_php/php_action/create.php], [crud_php/php_action/db_connect.php], and so on.

The current file structure should look like the below if you have followed the steps correctly:

CRUD_PHP_FOLDER

The video displays you to create a project folder and files for this tutorial.

4. PHP CRUD Part 4 Database Connection

The db_connect.php file i.e. [php_action/db_connect.php], this file contains a database connection. In this application, the db_connect.php file will be used to perform any action for CRUD. Such as connecting to the database, executing the query, and closing the connection.


<?php 

$localhost = "127.0.0.1"; 
$username = "root"; 
$password = ""; 
$dbname = "php_crud"; 

// create connection 
$connect = new mysqli($localhost, $username, $password, $dbname); 

// check connection 
if($connect->connect_error) {
	die("connection failed : " . $connect->connect_error);
} else {
	// echo "Successfully Connected";
}

?>

5. PHP CRUD Part 5 Create

5.1 Adding “Add Member” Button and “Action” button

To start with the create.php page we need a button that will lead to create.php page. Open index.php file which we created in Chapter 3 in this tutorial. And add an “Add Member” button at the top of the table, and an “Edit”, and “Remove” buttons at each row of the table.

Now the index.php file’s code should look like below, the highlighted code is what we need to implement in this tutorial.



<?php require_once 'php_action/db_connect.php'; ?>

<!DOCTYPE html>
<html>
<head>
	<title>PHP CRUD</title>

	<style type="text/css">
		.manageMember {
			width: 50%;
			margin: auto;
		}

		table {
			width: 100%;
			margin-top: 20px;
		}

	</style>

</head>
<body>

<div class="manageMember">
	<a href="create.php"><button type="button">Add Member</button></a>
	<table border="1" cellspacing="0" cellpadding="0">
		<thead>
			<tr>
				<th>Name</th>
				<th>Age</th>
				<th>Contact</th>
				<th>Option</th>
			</tr>
		</thead>
		<tbody>
			
		</tbody>
	</table>
</div>

</body>
</html>

Now if you go to the index.php page, you’ll see the “Add member” button. Eventually, the create.php is created at Chapter 3 and it will lead to a blank page when you click the “Add Member” button. In the next step, we will create a form to enter the member information into the system and add the member’s information to the database.

add member btn

5.2 Creating a Create page

In create.php file which you created in Chapter 3. This file contains an HTML form where the user’s input data will pass to the server side and add the information to the database.

The first part of this code is to create an HTML form with the required input field and pass the data to the server.


<!DOCTYPE html>
<html>
<head>
	<title>Add Member</title>

	<style type="text/css">
		fieldset {
			margin: auto;
			margin-top: 100px;
			width: 50%;
		}

		table tr th {
			padding-top: 20px;
		}
	</style>

</head>
<body>

<fieldset>
	<legend>Add Member</legend>

	<form action="php_action/create.php" method="post">
		<table cellspacing="0" cellpadding="0">
			<tr>
				<th>First Name</th>
				<td><input type="text" name="fname" placeholder="First Name" /></td>
			</tr>		
			<tr>
				<th>Last Name</th>
				<td><input type="text" name="lname" placeholder="Last Name" /></td>
			</tr>
			<tr>
				<th>Age</th>
				<td><input type="text" name="age" placeholder="Age" /></td>
			</tr>
			<tr>
				<th>Contact</th>
				<td><input type="text" name="contact" placeholder="Contact" /></td>
			</tr>
			<tr>
				<td><button type="submit">Save Changes</button></td>
				<td><a href="index.php"><button type="button">Back</button></a></td>
			</tr>
		</table>
	</form>

</fieldset>

</body>
</html>


The second part of this code insert process happens. Look through the codes and we will go through them afterward:


<?php 

require_once 'db_connect.php';

if($_POST) {
	$fname = $_POST['fname'];
	$lname = $_POST['lname'];
	$age = $_POST['age'];
	$contact = $_POST['contact'];

	$sql = "INSERT INTO members (fname, lname, contact, age, active) VALUES ('$fname', '$lname', '$contact', '$age', 1)";
	if($connect->query($sql) === TRUE) {
		echo "<p>New Record Successfully Created</p>";
		echo "<a href='../create.php'><button type='button'>Back</button></a>";
		echo "<a href='../index.php'><button type='button'>Home</button></a>";
	} else {
		echo "Error " . $sql . ' ' . $connect->connect_error;
	}

	$connect->close();
}

?>

Let us look at the beginning of the code. It first checks if the form is submitted by using a $_POST global variable. If a form is submitted then it inserts the data into the database by using $_POST. And check if the query is executed successfully then it displays a successful message and link button.

The end result should look like this if you have followed the instruction correctly. Click on Add Member on the index page and enter the member information into the input field. Click on the Save Changes button.

create

After creating some records by entering the member information, you should be able to see a CRUD grid as below:

create2

6. PHP CRUD Part 6 Retrieve

In the index.php page, we are going to retrieve the data that are stored in the database. This part is quite easy. We need a database connection file to execute the SQL command.
The highlighted codes are created for the edit and remove buttons. You can copy all the codes below.


<?php require_once 'php_action/db_connect.php'; ?>

<!DOCTYPE html>
<html>
<head>
	<title>PHP CRUD</title>

	<style type="text/css">
		.manageMember {
			width: 50%;
			margin: auto;
		}

		table {
			width: 100%;
			margin-top: 20px;
		}

	</style>

</head>
<body>

<div class="manageMember">
	<a href="create.php"><button type="button">Add Member</button></a>
	<table border="1" cellspacing="0" cellpadding="0">
		<thead>
			<tr>
				<th>Name</th>
				<th>Age</th>
				<th>Contact</th>
				<th>Option</th>
			</tr>
		</thead>
		<tbody>
			<?php
			$sql = "SELECT * FROM members WHERE active = 1";
			$result = $connect->query($sql);

			if($result->num_rows > 0) {
				while($row = $result->fetch_assoc()) {
					echo "<tr>
						<td>".$row['fname']." ".$row['lname']."</td>
						<td>".$row['age']."</td>
						<td>".$row['contact']."</td>
						<td>
							<a href='edit.php?id=".$row['id']."'><button type='button'>Edit</button></a>
							<a href='remove.php?id=".$row['id']."'><button type='button'>Remove</button></a>
						</td>
					</tr>";
				}
			} else {
				echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
			}
			?>
		</tbody>
	</table>
</div>

</body>
</html>

Now if you open this page “index.php”, you should see the member’s information on the table. As well as you should notice the “Edit” and “Remove” buttons at each table row data. They are not functional for this part. In the next part, we are going to learn about the update functionality for this tutorial.

index

7. PHP CRUD Part 7 Update

Go to edit.php file in [crud_php/edit.php] which was creating in Chapter 3. We will teach in two parts; the first part creating HTML form, and the second part server-side processing. The first part of the code is an HTML form to update the information of members. But it will not only update the data, but it will also display the member information. Copy the code below to the edit.php file at [crud_php/edit.php]:


<?php 

require_once 'php_action/db_connect.php';

if($_GET['id']) {
	$id = $_GET['id'];

	$sql = "SELECT * FROM members WHERE id = {$id}";
	$result = $connect->query($sql);

	$data = $result->fetch_assoc();

	$connect->close();

?>

<!DOCTYPE html>
<html>
<head>
	<title>Edit Member</title>

	<style type="text/css">
		fieldset {
			margin: auto;
			margin-top: 100px;
			width: 50%;
		}

		table tr th {
			padding-top: 20px;
		}
	</style>

</head>
<body>

<fieldset>
	<legend>Edit Member</legend>

	<form action="php_action/update.php" method="post">
		<table cellspacing="0" cellpadding="0">
			<tr>
				<th>First Name</th>
				<td><input type="text" name="fname" placeholder="First Name" value="<?php echo $data['fname'] ?>" /></td>
			</tr>		
			<tr>
				<th>Last Name</th>
				<td><input type="text" name="lname" placeholder="Last Name" value="<?php echo $data['lname'] ?>" /></td>
			</tr>
			<tr>
				<th>Age</th>
				<td><input type="text" name="age" placeholder="Age" value="<?php echo $data['age'] ?>" /></td>
			</tr>
			<tr>
				<th>Contact</th>
				<td><input type="text" name="contact" placeholder="Contact" value="<?php echo $data['contact'] ?>" /></td>
			</tr>
			<tr>
				<input type="hidden" name="id" value="<?php echo $data['id']?>" />
				<td><button type="submit">Save Changes</button></td>
				<td><a href="index.php"><button type="button">Back</button></a></td>
			</tr>
		</table>
	</form>

</fieldset>

</body>
</html>

<?php
}
?>

Let’s look at the code. At the beginning of the code, it catches the $id from a $_GET request. Then it fetches the information by that $id variable. After the data is retrieved from the database, the information is added to the input field. As well as the new input field is also appended to a name “id” to match the specific member data when the form is submitted.

In the Second part, the data update process is coded here. Open the update.php file in crud_php/php_action/update.php which was creating in Chapter 3. Open the file and copy and paste these codes.


<?php 

require_once 'db_connect.php';

if($_POST) {
	$fname = $_POST['fname'];
	$lname = $_POST['lname'];
	$age = $_POST['age'];
	$contact = $_POST['contact'];

	$id = $_POST['id'];

	$sql = "UPDATE members SET fname = '$fname', lname = '$lname', age = '$age', contact = '$contact' WHERE id = {$id}";
	if($connect->query($sql) === TRUE) {
		echo "<p>Succcessfully Updated</p>";
		echo "<a href='../edit.php?id=".$id."'><button type='button'>Back</button></a>";
		echo "<a href='../index.php'><button type='button'>Home</button></a>";
	} else {
		echo "Erorr while updating record : ". $connect->error;
	}

	$connect->close();

}

?>

Let us look at the beginning of the code. It first checks if the form is submitted by using a $_POST global variable. If a form is submitted then it updates the data in the database by using $_POST. And check if the query is executed successfully then it displays a successful message and link button.

If you followed the step correctly then your edit.php file should look like the below:

update

8. PHP CRUD Part 8 Remove

Go to remove.php file in [crud_php/remove.php] which was creating in Chapter 3. The logic is the same as we learned in Chapter 7 Update . In the first part, we’ll create HTML, and in the second part a server-side processing file. Copy the code below to the edit.php file at [crud_php/remove.php]:


<?php 

require_once 'php_action/db_connect.php';

if($_GET['id']) {
	$id = $_GET['id'];

	$sql = "SELECT * FROM members WHERE id = {$id}";
	$result = $connect->query($sql);
	$data = $result->fetch_assoc();

	$connect->close();
?>

<!DOCTYPE html>
<html>
<head>
	<title>Remove Member</title>
</head>
<body>

<h3>Do you really want to remove ?</h3>
<form action="php_action/remove.php" method="post">

	<input type="hidden" name="id" value="<?php echo $data['id'] ?>" />
	<button type="submit">Save Changes</button>
	<a href="index.php"><button type="button">Back</button></a>
</form>

</body>
</html>

<?php
}
?>

Let’s look at the code. At the beginning of the code, it catches the $id from a $_GET request. Then it fetches the information by that $id variable. After the data is retrieved from the database, a new input field is also appended named “id” to match the specific member data when the form is submitted.

If you followed correctly, then the remove.php page should be similar to the below:

remove



<?php 

require_once 'db_connect.php';

if($_POST) {
	$id = $_POST['id'];

	$sql = "UPDATE members SET active = 2 WHERE id = {$id}";
	if($connect->query($sql) === TRUE) {
		echo "<p>Successfully removed!!</p>";
		echo "<a href='../index.php'><button type='button'>Back</button></a>";
	} else {
		echo "Error updating record : " . $connect->error;
	}

	$connect->close();
}

?>


Let’s look at the beginning of the code. It first checks if the form is submitted by using a $_POST global variable. If a form is submitted then it removes the data. And checks if the query is executed successfully then it displays a successful message and button link.

Download Source Code!!!!

Download

Submitting the form with Ajax

AJAX (Asynchronous JavaScript and XML) is a great technique usually used for updating the portion of a web page without refreshing the whole page. The help of the Ajax technique it will make the web application much better, faster, and more interactive. To submit the form with Ajax we will be working with procedural PHP, HTML, and Ajax.

At the end of this tutorial, we’ll provide you with a source code and database link.

Table of Content

  1. Setting up assets file and project folder
  2. Configure Database
  3. Creating the HTML form page to display
  4. Creating the PHP file to process
  5. Submitting the form using Ajax

1. Setting up assets file and Project folder

In this part, we assume that you have downloaded the jQuery file from a jQuery official website. If you haven’t downloaded it yet, then click here to download.

First of all, create the project folder named “submit_from_using_ajax” or something else you wanted and inside that project, folder create another folder named “jquery” i.e. [submit_form_using_ajax/jquery] which contains the downloaded jquery plugin. Now move or come back to the project folder directory and create three files namely index.php, add.php, and add.js e.g. [submit_form_using_ajax/index.php], [submit_form_using_ajax/add.php], and [submit_form_using_ajax/add.js]. If you have followed the instruction correctly then the folder and file structure should look like the below:

submit_form_using_ajax_file_structure

2. Configure Database

Database Name: members
Table Name: members
Table Column: id, fname, lname, contact, active

Copy and paste the following SQL command into your MySQL database to create a database and table.


CREATE DATABASE `members`;

CREATE TABLE `members`.`members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(255) NOT NULL,
  `lname` varchar(255) NOT NULL,
  `contact` varchar(20) NOT NULL,
  `active` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3;

3. Creating the HTML form

We’ll be using HTML form elements to create a simple form since designing is not our main concern. Firstly, go to the index.php file which was created at chapter 1. Copy and paste these codes into the index.php file and we will go through them afterward:


<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>


<form action="add.php" method="post" id="submitForm">
	<label>First Name</label>
	<input type="text" name="fname" id="fname" />
	

	<label>Last Name</label>
	<input type="text" name="lname" id="lname" />

	

	<label>Contact</label>
	<input type="text" name="contact" id="contact" />	

	

	<button type="submit">Submit</button>

</form>


<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</body>
</html>

In the above codes, the input field and button are kept inside the form element. After that, the action of the form is defined as add.php and the method is defined as “POST” so when submitting the form, the input value will not be visible to the users. Lastly, the form id is defined as submitForm, which will be using in Ajax’s part in Chapter 5. The highlighted codes are crucial to run the Ajax function. The first script links to the jQuery plugin and the second script links to add.js.

Whenever you submit the form, the page will redirect to a blank page. That part will be done in the next chapter.

4. Creating the PHP file to process

This part is straightforward. To process the form, we will be creating an uncomplicated PHP script to process the form. Copy and paste these codes into add.php file and we will go through them afterward:


<?php 
   if($_POST) { $localhost = "127.0.0.1"; $username = "root"; $password = ""; $dbname = "members"; // connect $connect = new mysqli($localhost, $username, $password, $dbname); // checking the connection if($connect->connect_error) {
		die("connection failed : " . $connect->connect_error);
	} else {
		// echo "Connected Successfully";
	}

	$fname = $_POST['fname'];
	$lname = $_POST['lname'];
	$contact = $_POST['contact'];

	$sql = "INSERT INTO members (fname, lname, contact) VALUES ('$fname', '$lname', '$contact')";
	if($connect->query($sql) == TRUE) {
		echo "Successfully added";
	} else {
		echo "Error while added the information";
	}

	$connect->close();
	// closing the database connection

}

?>

This tutorial guides you to simply submit the Ajax form. Hence, the form validation is not implemented in this script. The first line of the script checks a form submitted using a $_POST variable furthermore, creates a database connection and executes the query. After that, it checks query is executed successfully and returns proper messages. At the end of the script, the opened database connection is closed to prevent an open database connection.

If you try to submit the form then the script will return proper messages.

5. Submitting the form using Ajax

Finally, we reached the main part of this tutorial. To submit the form with Ajax, we’ll need to do several things in our JavaScript file. Firstly, we need to capture the forms’ submit button so that the default action does not occur. Secondly, we need to pass the form data to the server by using Ajax and display an appropriate message. For now, copy and paste these codes into the add.js file and we will go through them afterward:


$(document).ready(function() {
	$("#submitForm").unbind('submit').bind('submit', function() {
		var form = $(this);

		var url = form.attr('action');
		var type = form.attr('method');

		// sending the request to server
		$.ajax({
			url: url,
			type: type,
			data: form.serialize(),
			dataType: 'text',
			success:function(response) {
				$("#submitForm")[0].reset();
				alert(response);
			}
		});

		return false;
	});
});

Now when you submit the form, the JavaScript code catches that event by #submitForm id which was created in Chapter 3. The variable form holds the input values, and the URL and type variable gets the form action and method values respectively. After that, the jquery built-in Ajax function will be used to send the data to a server which was defined in a form element. The serialize function is used to convert the values into an array instead of pulling the form data individually.

The below video displays a detailed tutorial for submitting the form using Ajax. We recommend you go through the above chapters and then watch this video to fully understand how the Ajax form works.

Download Source Code!!!

Download

Online Inventory Management Software with PHP, Open Source

Online Inventory Management Software is an open-source project developed by procedural PHP, MySQL, bootstrap, and jquery. This application is based on a web application and developed with procedural PHP, MySQL database, jquery, datatables plugins, and Bootstrap. This application provides users to manage brands, categories, products, orders, and reports. This system provides the best inventory management software features. This system can be also used for small businesses. It is free web-based inventory management software.

On the brand’s page, the admin can add, update, and remove the brand’s information. In the product section, the admin can add product information and manage the stock. In the order section, the application will manage the stock of the product and generates the total amount of payment to be paid by the client. The application can also generate the orders report based on the month you select.

Requirements

  • PHP Version +5.4.4
  • Web Server ( Recommended: Apache with PHP and Mysqli )

Features

  • View of the total number of brands, categories, products, and orders.
  • Add, update, and remove brand information.
  • Add, update, and remove categories information.
  • Add, update, and remove product details.
  • Add, update, and remove order details.
  • Print orders invoice.
  • Update order payment.
  • Generate the orders report by selecting specific start and end dates.
  • Change Password
  • Change Username

Users

  • Admin
    • Username: admin
    • password: password

Change the VAT

To change the vat number, all you have to do is go to the order.js file which is located at [custom/js/order.js] and search for subAmount function. In line 555, you will see the VAT variable, change the VAT number that you desired. To change the vat number in the front end of the application, go to orders.php, and at line 369, you will see the VAT label, change it to the number you desire.

Download Online Stock Management System

Please Read:

While creating the database for this system, either you can create the name of the database as a stock or change the name at the php_action/db_connect.php file. As shown below:


<php 
$localhost = "127.0.0.1"; 
$username = "root"; 
$password = ""; 
$dbname = "stock"; 

// db connection 
$connect = new mysqli($localhost, $username, $password, $dbname);

// check connection 
if($connect->connect_error) {
   die("Connection Failed : " . $connect->connect_error);
} else {
   // echo "Successfully connected";
}

?>

System Live Preview

Live Preview

For Source Code:

Download

Datatables CRUD with PHP, MYSQLI, BOOTSTRAP

Datatables is a plug-in to enhance the HTML table interaction and provide adaptable tools. Datatables CRUD (Create, Retrieve Update Delete) will improve your application in terms of readability, Better UI, and other advantages. There are many benefits of using this plug-in, but for this tutorial, we will be discussing a simple Create, Retrieve, Update, and Delete (CRUD).

Table of Content

  1. Introduction
  2. Configure Database
  3. Setting assets file and project folder
  4. Database Connection
  5. Create Member
  6. Retrieve Data
  7. Remove Member
  8. Update Member

1. Introduction

In this section, we are going to develop a CRUD (Create, Retrieve, Update, Delete) PHP operation with the Datatable jquery plugin which will improve the table flexibility. In the future as a web developer, you will be working with these basic functionalities namely create, retrieve, update, and delete. The CRUD logic is relevant to CRUD with PHP MYSQLI Tutorial. The Ajax and Datatables are only used to raise the performance of CRUD operations. To understand how CRUD operation works in the Datatable jquery plugin, We recommend you go through each part of this tutorial.

The below video illustrates the final system of this tutorial. The source code of this application will be provided at the end of this tutorial.

2. Configure Database

Database Name: datatables_crud
Table Name: members
Table Column: id, name, contact, address, active

To create the database for this tutorial, you can either download the SQL command by clicking the button which is provided at the end of this tutorial or manually copy and paste the following SQL command into your MYSQL database.


CREATE DATABASE `datatables_crud`;

CREATE TABLE `datatables_crud`.`members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`contact` varchar(20) NOT NULL,
`active` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

3. Setting assets file and project folder

In this part, we will be creating a folder and file within this project folder. In this project, there will be three folders and one file. First of all, create three folders and a file namely assets, custom, and php_action and index.php as a file i.e. : [datatables_crud/assests], [datatables_crud/custom], [datatables_crud/php_action], and [datatables_crud/index.php].

Firstly, In an assets folder, bootstrap, datatables, and jquery files are included. Please download the files and keep them in this folder. Secondly, In a custom folder, CSS and js folder are required and within that folder, each folder contains one file i.e. [datatables_crud/custom/css/style.css] and [datatables_crud/custom/js/index.js] respectively. Finally, The php_action folder which includes six files and they are create.php, db_connect.php, getSelectedMember.php, remove.php, retrieve.php, and update.php.

If you have followed the steps correctly then the working folders and files structure would look like the below:

datatables_crud_folder_structure

4. Database Connection

In db_connect.php file i.e. [php_action/db_connect.php], contains a database connection. In this application, the db_connect.php file will be used to perform any action for CRUD. Such as connecting to the database, executing the query, and closing the connection. If you have a different database name for this tutorial, please change the name of the database in the db_connect.php file which is highlighted below.


<?php 

$servername = "127.0.0.1"; 
$username = "root"; 
$password = ""; 
$dbname = "datatables_crud"; 

// create connection 
$connect = new mysqli($servername, $username, $password, $dbname); 

// check connection 
if($connect->connect_error) {
die("Connection Failed : " . $connect->connect_error);
} else {
// echo "Successfully Connected";
}

?>

5. Create Member

5.1 Add Member Button and Linking to Assets file

To start with inserting the member’s information into the system, First of all, we’ll create a bootstrap pop-up modal containing the input fields within a form and go to index.php file i.e. [datatables_crud/index.php], and add an “Add Member” button at the top of the table. Please check your index.php file plugin’s link which is necessary to run the various plugin for this tutorial.


<!DOCTYPE html>
<html>
<head>
<title>CRUD SYSTEM</title>

<!-- bootstrap css -->
<link rel="stylesheet" type="text/css" href="assests/bootstrap/css/bootstrap.min.css">
<!-- datatables css -->
<link rel="stylesheet" type="text/css" href="assests/datatables/datatables.min.css">

</head>
<body>

<div class="container">
   <div class="row">
      <div class="col-md-12">

         <center><h1 class="page-header">CRUD System <small>DataTables</small> </h1> </center>

         <div class="removeMessages"></div>

         <button class="btn btn-default pull pull-right" data-toggle="modal" data-target="#addMember" id="addMemberModalBtn">
            <span class="glyphicon glyphicon-plus-sign"></span>	Add Member
         </button>

         <br /> <br /> <br />

         <table class="table" id="manageMemberTable">					
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Name</th>													
                  <th>Address</th>
                  <th>Contact</th>								
                  <th>Active</th>
                  <th>Option</th>
               </tr>
            </thead>
         </table>
      </div>
   </div>
</div>

<!-- add modal -->
<div class="modal fade" tabindex="-1" role="dialog" id="addMember">
   <div class="modal-dialog" role="document">
   <div class="modal-content">
   <div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
   <h4 class="modal-title"><span class="glyphicon glyphicon-plus-sign"></span>	Add Member</h4>
   </div>
   
   <form class="form-horizontal" action="php_action/create.php" method="POST" id="createMemberForm">

   <div class="modal-body">
      <div class="messages"></div>

         <div class="form-group"> <!--/here teh addclass has-error will appear -->
         <label for="name" class="col-sm-2 control-label">Name</label>
         <div class="col-sm-10"> 
         <input type="text" class="form-control" id="name" name="name" placeholder="Name">
         <!-- here the text will apper -->
         </div>
         </div>
         <div class="form-group">
         <label for="address" class="col-sm-2 control-label">Address</label>
         <div class="col-sm-10">
         <input type="text" class="form-control" id="address" name="address" placeholder="Address">
         </div>
         </div>
         <div class="form-group">
         <label for="contact" class="col-sm-2 control-label">Contact</label>
         <div class="col-sm-10">
         <input type="text" class="form-control" id="contact" name="contact" placeholder="Contact">
         </div>
         </div>
         <div class="form-group">
         <label for="active" class="col-sm-2 control-label">Active</label>
         <div class="col-sm-10">
         <select class="form-control" name="active" id="active">
            <option value="">~~SELECT~~</option>
            <option value="1">Activate</option>
            <option value="2">Deactivate</option>
         </select>
         </div>
         </div>			 		

   </div>
   <div class="modal-footer">
   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   <button type="submit" class="btn btn-primary">Save changes</button>
   </div>
   </form> 
   </div><!-- /.modal-content -->
   </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- /add modal -->

<!-- jquery plugin -->
<script type="text/javascript" src="assests/jquery/jquery.min.js"></script>
<!-- bootstrap js -->
<script type="text/javascript" src="assests/bootstrap/js/bootstrap.min.js"></script>
<!-- datatables js -->
<script type="text/javascript" src="assests/datatables/datatables.min.js"></script>
<!-- include custom index.js -->
<script type="text/javascript" src="custom/js/index.js"></script>

</body>
</html>

Copy and paste these codes into your index.php file and navigate to this page. Click on add member button to inspect if the bootstrap modal is working correctly.

5.2 Creating a PHP file to insert the data into the database

In these codes, the insert process happens. Look through the codes and we will go through them afterward:


<?php 

require_once 'db_connect.php'; 

//if form is submitted 

if($_POST) { 
   
   $validator = array('success' => false, 'messages' => array());

   $name = $_POST['name'];
   $address = $_POST['address'];
   $contact = $_POST['contact'];
   $active = $_POST['active'];

   $sql = "INSERT INTO members (name, contact, address, active) VALUES ('$name', '$contact', '$address', '$active')";
   $query = $connect->query($sql);

   if($query === TRUE) {			
      $validator['success'] = true;
      $validator['messages'] = "Successfully Added";		
   } else {		
      $validator['success'] = false;
      $validator['messages'] = "Error while adding the member information";
   }

   // close the database connection
   $connect->close();

   echo json_encode($validator);

}

Let us look at the beginning of the codes, It checks if the form is submitted by using a $_POST global variable. If the form is submitted then it inserts the data into the database and checks if the query is executed successfully. At the end of the query, the built-in json_encode function will pass the result of the action.

5.3 Create an Ajax file to pass the data to the server


<?php 
// global the manage memeber table 
var manageMemberTable;

$(document).ready(function() {
manageMemberTable = $("#manageMemberTable").DataTable();

$("#addMemberModalBtn").on('click', function() {
   // reset the form 
   $("#createMemberForm")[0].reset();
   // remove the error 
   $(".form-group").removeClass('has-error').removeClass('has-success');
   $(".text-danger").remove();
   // empty the message div
   $(".messages").html("");

   // submit form
   $("#createMemberForm").unbind('submit').bind('submit', function() {

      $(".text-danger").remove();

      var form = $(this);

      // validation
      var name = $("#name").val();
      var address = $("#address").val();
      var contact = $("#contact").val();
      var active = $("#active").val();

      if(name == "") {
         $("#name").closest('.form-group').addClass('has-error');
         $("#name").after('The Name field is required');
      } else {
         $("#name").closest('.form-group').removeClass('has-error');
         $("#name").closest('.form-group').addClass('has-success');				
      }

      if(address == "") {
         $("#address").closest('.form-group').addClass('has-error');
         $("#address").after('The Address field is required');
      } else {
         $("#address").closest('.form-group').removeClass('has-error');
         $("#address").closest('.form-group').addClass('has-success');				
      }

      if(contact == "") {
         $("#contact").closest('.form-group').addClass('has-error');
         $("#contact").after('The Contact field is required');
      } else {
         $("#contact").closest('.form-group').removeClass('has-error');
         $("#contact").closest('.form-group').addClass('has-success');				
      }

      if(active == "") {
         $("#active").closest('.form-group').addClass('has-error');
         $("#active").after('The Active field is required');
      } else {
         $("#active").closest('.form-group').removeClass('has-error');
         $("#active").closest('.form-group').addClass('has-success');				
      }

      if(name && address && contact && active) {
         //submi the form to server
         $.ajax({
            url : form.attr('action'),
            type : form.attr('method'),
            data : form.serialize(),
            dataType : 'json',
            success:function(response) {

               // remove the error 
               $(".form-group").removeClass('has-error').removeClass('has-success');

               if(response.success == true) {
                  $(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                     '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                     '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                  '</div>');

                  // reset the form
                  $("#createMemberForm")[0].reset();		

                  // reload the datatables
                  manageMemberTable.ajax.reload(null, false);
                  // this function is built in function of datatables;
               } else {
                  $(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                     '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                     '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                  '</div>');
               } // /else
            } // success 
         }); // ajax subit 				
      } /// if


      return false;
   }); // /submit form for create member
}); // /add modal

});

The manageMemberTable is initiated as a global variable to call in another function. This concept will be cleared up in the next part. The #addMemberModalBtn click function will clear the input field and inside that function, the #createMemberForm onsubmit function will validate the input field and send the data into the server with the help of Ajax when the form is submitted by users.

6. Retrieve Data

This part is easy, go to the [custom/js/index.js] file, and in that file, we will need to call the [php_action/retrieve.php] file. In this section, there are two steps to fetch the data from the database. Look through the codes and we will go through them afterward:


<?php 

require_once 'db_connect.php';

$output = array('data' => array());

$sql = "SELECT * FROM members";
$query = $connect->query($sql);

$x = 1;
while ($row = $query->fetch_assoc()) {
$active = '';
if($row['active'] == 1) {
   $active = '<label class="label label-success">Active</label>';
} else {
   $active = '<label class="label label-danger">Deactive</label>'; 
}

$actionButton = '
<div class="btn-group">
   <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
   Action <span class="caret"></span>
   </button>
   <ul class="dropdown-menu">
   <li><a type="button" data-toggle="modal" data-target="#editMemberModal" onclick="editMember('.$row['id'].')"> <span class="glyphicon glyphicon-edit"></span> Edit</a></li>
   <li><a type="button" data-toggle="modal" data-target="#removeMemberModal" onclick="removeMember('.$row['id'].')"> <span class="glyphicon glyphicon-trash"></span> Remove</a></li>	 
   </ul>
</div>';

$output['data'][] = array(
   $x,
   $row['name'],
   $row['address'],
   $row['contact'],
   $active,
   $actionButton
);

$x++;
}

// database connection close
$connect->close();

echo json_encode($output);

?>

Firstly, In the above codes, the data is fetched from the database and stored as an associative array. The fetched data is appended into an array variable. At the end of the script, the fetched data is converted into a JSON format. The bootstrap dropdown button which includes the javascript onclick function will be justified in the next part.

Secondly, This is the most important part. We will be using an “Ajax” built-in function of a datatable to retrieve the data from the server i.e. retrieve.php file. To use the Ajax function, we will be writing a bit of code where the datatable function is instantiated. Look through the highlighted code.


manageMemberTable = $("#manageMemberTable").DataTable({
   "ajax": "php_action/retrieve.php",
   "order": []
});

A video demonstration to retrieve a data through datatable function.

7. Remove Member

Go to the index.php file in [datatables_crud/index.php]. The logic is simple. First of all, we’ll create a remove button to pop up a modal with a confirmation button. Secondly, we’ll create a server-side processing script file that will remove the selected member’s information from the database Lastly, submit the form via Ajax.

7.1 Creating the remove modal form

Go to the index.php file and create a pop-up bootstrap modal with a confirmation button inside a form. When the remove button is clicked this remove confirmation modal should be displayed. For now, Copy and paste them into the index.php file after adding the modal code.



<!-- remove modal -->
<div class="modal fade" tabindex="-1" role="dialog" id="removeMemberModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title"><span class="glyphicon glyphicon-trash"></span> Remove Member</h4>
</div>
<div class="modal-body">
<p>Do you really want to remove ?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="removeBtn">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- /remove modal -->


7.2 Creating the remove.php file

Go to remove.php in the php_action folder. Copy and paste these codes into the remove.php file.


<?php 

require_once 'db_connect.php';

$output = array('success' => false, 'messages' => array());

$memberId = $_POST['member_id'];

$sql = "DELETE FROM members WHERE id = {$memberId}";
$query = $connect->query($sql);
if($query === TRUE) {
$output['success'] = true;
$output['messages'] = 'Successfully removed';
} else {
$output['success'] = false;
$output['messages'] = 'Error while removing the member information';
}

// close database connection
$connect->close();

echo json_encode($output);

?>

7.3 Creating the remove function in Ajax

In this part, create a javascript function as remove member.

[css autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” highlight=”” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”true” title=”custom/js/index.js”]
// global the manage memeber table
var manageMemberTable;

$(document).ready(function() { …
});

function removeMember(id = null) {
if(id) {
// click on remove button
$("#removeBtn").unbind(‘click’).bind(‘click’, function() {
$.ajax({
url: ‘php_action/remove.php’,
type: ‘post’,
data: {member_id : id},
dataType: ‘json’,
success:function(response) {
if(response.success == true) {
$(".removeMessages").html(‘<div class="alert alert-success alert-dismissible" role="alert">’+
‘<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>’+
‘<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>’+response.messages+
‘</div>’);

// refresh the table
manageMemberTable.ajax.reload(null, false);

// close the modal
$("#removeMemberModal").modal(‘hide’);

} else {
$(".removeMessages").html(‘<div class="alert alert-warning alert-dismissible" role="alert">’+
‘<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>’+
‘<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>’+response.messages+
‘</div>’);
}
}
});
}); // click remove btn
} else {
alert(‘Error: Refresh the page again’);
}
}

8. Update Member

8.1 Creating update modal form and fetching particular member data

In this part, we are going to get the particular member’s information whenever the edit button is clicked. When clicking that button the editMember function is invoked and it will fetch the member’s information for displaying in the input fields and updating the member’s information.

The logic is simple, In index.js create an editMember method which should accept one parameter namely member id. By using that id it should be able to fetch and display the member’s information with the help of Ajax. As well as we need to create a pop-up modal on the index page i.e. index.php to display and update the member’s information. To do this, we need to write some codes in getSelectedMember.php, index.js, and index.php files.

Firstly, go to the getSelectedMember.php file which is located at [php_action/getSelectedMember.php]. This code will retrieve a particular member’s information from the database by using the particular member’s id. Copy and paste these codes and we will go through them afterward:


<?php 

require_once 'db_connect.php';

$memberId = $_POST['member_id'];

$sql = "SELECT * FROM members WHERE id = $memberId";
$query = $connect->query($sql);
$result = $query->fetch_assoc();

$connect->close();

echo json_encode($result);

?>

In the above codes, the server gets the member id from the $_POST variable. Through that id, the script executes the query and returns the associative data into a JSON format.

Secondly, Go to the index.js file which is located at [custom/js/index.js]. In this file, an editMember method will get a member id and pass it to the server for getting the data. Copy and paste these codes and we will go through them afterward:


// global the manage memeber table 
var manageMemberTable;

$(document).ready(function() {...
});

function removeMember(id = null) { ...
}

function editMember(id = null) {
   if(id) {
      // remove the error 
      $(".form-group").removeClass('has-error').removeClass('has-success');
      $(".text-danger").remove();
      // empty the message div
      $(".edit-messages").html("");

      // remove the id
      $("#member_id").remove();

      // fetch the member data
      $.ajax({
         url: 'php_action/getSelectedMember.php',
         type: 'post',
         data: {member_id : id},
         dataType: 'json',
         success:function(response) {
            $("#editName").val(response.name);

            $("#editAddress").val(response.address);

            $("#editContact").val(response.contact);

            $("#editActive").val(response.active);	

            // member id 
            $(".editMemberModal").append('<input type="hidden" name="member_id" id="member_id" value="'+response.id+'"/>');				

         } // /success
      }); // /fetch selected member info

   } else {
      alert("Error : Refresh the page again");
   }
}


In the above codes, the editMember function requires one parameter as member id. From that id, the function will fetch the member information, display the value in the input field and create a hidden input field with the member id value.

8.2 Submitting the form via Ajax

In this section, when a form is submitted, the onsubmit function is invoked. This function will verify the input field and update the member’s information.

Firstly, go to the [custom/js/index.js] file and copy and paste the highlight codes inside the editMember function as below and we’ll go through them afterward:


function editMember(id = null) {
   if(id) {

      // remove the error 
      $(".form-group").removeClass('has-error').removeClass('has-success');
      $(".text-danger").remove();
      // empty the message div
      $(".edit-messages").html("");

      // remove the id
      $("#member_id").remove();

      // fetch the member data
      $.ajax({
         url: 'php_action/getSelectedMember.php',
         type: 'post',
         data: {member_id : id},
         dataType: 'json',
         success:function(response) {
            $("#editName").val(response.name);

            $("#editAddress").val(response.address);

            $("#editContact").val(response.contact);

            $("#editActive").val(response.active);	

            // mmeber id 
            $(".editMemberModal").append('<input type="hidden" name="member_id" id="member_id" value="'+response.id+'"/>');

            // here update the member data
            $("#updateMemberForm").unbind('submit').bind('submit', function() {
               // remove error messages
               $(".text-danger").remove();

               var form = $(this);

               // validation
               var editName = $("#editName").val();
               var editAddress = $("#editAddress").val();
               var editContact = $("#editContact").val();
               var editActive = $("#editActive").val();

               if(editName == "") {
                  $("#editName").closest('.form-group').addClass('has-error');
                  $("#editName").after('<p class="text-danger">The Name field is required</p>');
               } else {
                  $("#editName").closest('.form-group').removeClass('has-error');
                  $("#editName").closest('.form-group').addClass('has-success');				
               }

               if(editAddress == "") {
                  $("#editAddress").closest('.form-group').addClass('has-error');
                  $("#editAddress").after('<p class="text-danger">The Address field is required</p>');
               } else {
                  $("#editAddress").closest('.form-group').removeClass('has-error');
                  $("#editAddress").closest('.form-group').addClass('has-success');				
               }

               if(editContact == "") {
                  $("#editContact").closest('.form-group').addClass('has-error');
                  $("#editContact").after('<p class="text-danger">The Contact field is required</p>');
               } else {
                  $("#editContact").closest('.form-group').removeClass('has-error');
                  $("#editContact").closest('.form-group').addClass('has-success');				
               }

               if(editActive == "") {
                  $("#editActive").closest('.form-group').addClass('has-error');
                  $("#editActive").after('<p class="text-danger">The Active field is required</p>');
               } else {
                  $("#editActive").closest('.form-group').removeClass('has-error');
                  $("#editActive").closest('.form-group').addClass('has-success');				
               }

               if(editName && editAddress && editContact && editActive) {
                  $.ajax({
                     url: form.attr('action'),
                     type: form.attr('method'),
                     data: form.serialize(),
                     dataType: 'json',
                     success:function(response) {
                        if(response.success == true) {
                           $(".edit-messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                              '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                              '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                           '</div>');

                           // reload the datatables
                           manageMemberTable.ajax.reload(null, false);
                           // this function is built in function of datatables;

                           // remove the error 
                           $(".form-group").removeClass('has-success').removeClass('has-error');
                           $(".text-danger").remove();
                        } else {
                           $(".edit-messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                              '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                              '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                           '</div>')
                        }
                     } // /success
                  }); // /ajax
               } // /if

               return false;
            });

         } // /success
      }); // /fetch selected member info

   } else {
      alert("Error : Refresh the page again");
   }
}

First of all, the edit member function gets the member id as a parameter, and through that id, it retrieves the member’s information. When the users submit the form, the submit function is invoked to verify the input field and update the member information.

This part is simple, we’re going to add the codes to the update.php file to update the member information in the database. Just copy and paste them into your update.php file and we’ll go through them afterward:


<?php 

require_once 'db_connect.php';

//if form is submitted
if($_POST) {	

   $validator = array('success' => false, 'messages' => array());

   $id = $_POST['member_id'];
   $name = $_POST['editName'];
   $address = $_POST['editAddress'];
   $contact = $_POST['editContact'];
   $active = $_POST['editActive'];

   $sql = "UPDATE members SET name = '$name', contact = '$contact', address = '$address', active = '$active' WHERE id = $id";
   $query = $connect->query($sql);

   if($query === TRUE) {			
      $validator['success'] = true;
      $validator['messages'] = "Successfully Added";		
   } else {		
      $validator['success'] = false;
      $validator['messages'] = "Error while adding the member information";
   }

   // close the database connection
   $connect->close();

   echo json_encode($validator);

}

?>

Download Source Code !!!

Download