Categories
Laravel

CRUD Operations In Laravel 8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 8. Laravel is one of the fastest-growing frameworks for PHP. Laravel 8 continues the improvements made in the previous stable release. Refer release notes to see the changes made in Laravel 8.

In this tutorial, You’ll learn to create the basic CRUD operations in Laravel. Follow the step-by-step guide to implement CRUD in Laravel 8.

What is CRUD?

When we are creating any dynamic web applications, it deals with some database operations such as Create, Read, Update, and Delete which are the four basic functions that we implement with the model. Hence, Software Engineers or Computer scientists often refer to these functions with the acronym CRUD .

  1. Install Laravel

First, let install Laravel using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel stock_management
  1. Configure the Database

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE='Your DB Name'
DB_USERNAME='Your DB UserName'
DB_PASSWORD='Your DB Password'
Code language: JavaScript (javascript)
  1. Create the Stock Model and Migration

Next we are going to create the model using the following artisan command which will create the Model and the corresponding migration file.

php artisan make:model Stock -m
Code language: CSS (css)

Open app/Models/Stock.php file and define the modal values in the $fillable prop.

app\Models\Stock.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Stock extends Model
{
    use HasFactory;
    public $fillable = [
        'product_name',
        'product_desc',
        'product_qty'
    ];
}

Code language: HTML, XML (xml)

The migration will be created under β€œdatabase/migrationsβ€œ. Edit the file with the code below to create Stock Table.

database/migrations/timestamp_create_stocks_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStocksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stocks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('product_name');
            $table->text('product_desc');
            $table->integer('product_qty');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('stocks');
    }
}
Code language: HTML, XML (xml)

Type the following command to run the migration.

php artisan migrate
  1. Create Seeder

Next we are going to add some dummy data to the stock table using laravel Seeder using the following artisan command.

php artisan make:seeder StockTableSeeder
Code language: CSS (css)

All seeders generated will be placed in the database/seeders directory.

database\seeders\StockTableSeeder.php

<?php

namespace Database\Seeders;

use App\Models\Stock;
use Illuminate\Database\Seeder;

class StockTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Stock::create([
            'product_name' => 'Twinty Pencil',
            'product_desc' => 'HB 5 Drawing Pencil',
            'product_qty' => 100,
        ]);
    }
}
Code language: HTML, XML (xml)

So, we have added the columns product_nameproduct_descproduct_qty values that will be stored in the database. Run the following command to execute StockTableSeeder :

php artisan db:seed --class=StockTableSeeder
Code language: JavaScript (javascript)
  1. Create Route and Resource Controller

Now, It’s time to create the logic for CRUD operations. We will use the Resource Controller to define the operations under the pre-defined methods within the Resource Controller. Run the following Artisan command to create the Stock resource controller.

php artisan make:controller StockController --resource
Code language: CSS (css)

In this step, Go to routes->web.php file, add the following line of code to direct the routes to Stock Controller.

<?php

use App\Http\Controllers\StockController;
use Illuminate\Support\Facades\Route;


// Redirects to the Stock Resource Controller
Route::get('/', function () {
    return redirect('/stocks');
});

Route::resource('stocks', StockController::class);
Code language: HTML, XML (xml)

Add the following lines of codes in StockController to manipulate the basic CRUD operations.

app\Http\Controllers\StockController.php

<?php

namespace App\Http\Controllers;

use App\Models\Stock;
use Illuminate\Http\Request;

class StockController extends Controller
{
    public function index()
    {
        $stocks = Stock::latest()->paginate(5);
        return view('stocks.index',compact('stocks'))->with('i', (request()->input('page', 1) - 1) * 5);
    }

    public function create()
    {
        return view('stocks.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_name' => 'required',
            'product_desc' => 'required',
            'product_qty' => 'required',
        ]);

        Stock::create($request->all());
        return redirect()->route('stocks.index')->with('success','Created Successfully.');
    }

    public function show(Stock $stock)
    {
        return view('stocks.show',compact('stock'));
    }


    public function edit(Stock $stock)
    {
        return view('stocks.edit',compact('stock'));
    }

    public function update(Request $request, Stock $stock)
    {
        $request->validate([
            'product_name' => 'required',
            'product_desc' => 'required',
            'product_qty' => 'required',
        ]);

        $stock->update($request->all());
        return redirect()->route('stocks.index')->with('success','Updated Successfully.');
    }


    public function destroy(Stock $stock)
    {
        $stock->delete();
        return redirect()->route('stocks.index')->with('success','Student deleted successfully.');
    }
}
Code language: HTML, XML (xml)
  1. Create the Views

Finally, create a folder Inside the resources\views directory as stocks within that folder, create the following five files.

  1. layout.blade.php
  2. index.blade.php
  3. create.blade.php
  4. edit.blade.php
  5. show.blade.php

layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 CRUD Application - bishrulhaq.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>

<div class="container">
    <div class="card" style="margin-top: 20px;">
        <div class="card-body">
        @yield('content')
        </div>
    </div>
</div>

</body>
</html>
Code language: HTML, XML (xml)

index.blade.php

@extends('stocks.layout')

@section('content')

    <div class="row">
        <div class="col-lg-12">
            <h2 class="text-center">Simple Stock Management Application | BH</h2>
        </div>
        <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;">
            <a class="btn btn-success " href="{{ route('stocks.create') }}"> Add Stock</a>
        </div>
    </div>

    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            {{ $message }}
        </div>
    @endif

    @if(sizeof($stocks) > 0)
        <table class="table table-bordered">
            <tr>
                <th>No</th>
                <th>Product Name</th>
                <th>Product Description</th>
                <th>Qty.</th>
                <th width="280px">More</th>
            </tr>
            @foreach ($stocks as $stock)
                <tr>
                    <td>{{ ++$i }}</td>
                    <td>{{ $stock->product_name }}</td>
                    <td>{{ $stock->product_desc }}</td>
                    <td>{{ $stock->product_qty }}</td>
                    <td>
                        <form action="{{ route('stocks.destroy',$stock->id) }}" method="POST">
                            <a class="btn btn-info" href="{{ route('stocks.show',$stock->id) }}">Show</a>
                            <a class="btn btn-primary" href="{{ route('stocks.edit',$stock->id) }}">Edit</a>
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </table>
    @else
        <div class="alert alert-alert">Start Adding to the Database.</div>
    @endif

    {!! $stocks->links() !!}

@endsection
Code language: HTML, XML (xml)

create.blade.php

@extends('stocks.layout')

@section('content')

<div class="row">
    <div class="col-lg-12">
        <h2 class="text-center">Add Stock</h2>
    </div>
    <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;">
        <a class="btn btn-primary" href="{{ route('stocks.index') }}"> Back</a>
    </div>
</div>

@if ($errors->any())
<div class="alert alert-danger">
    <strong>Oops!</strong> There were some problems with your input.<br><br>
    <ul>
        @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>
@endif

<form action="{{ route('stocks.store') }}" method="POST">
    @csrf

    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Product Name:</strong>
                <input type="text" name="product_name" class="form-control" placeholder="Product Name">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Product Description:</strong>
                <textarea class="form-control" style="height:150px" name="product_desc" placeholder="Product Description"></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Qty:</strong>
                <input type="number" class="form-control" name="product_qty" placeholder="Quantity">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>

</form>
@endsection
Code language: HTML, XML (xml)

edit.blade.php

@extends('stocks.layout')

@section('content')

    <div class="row">
        <div class="col-lg-12">
            <h2 class="text-center">Edit Stock</h2>
        </div>
        <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;">
            <a class="btn btn-primary" href="{{ route('stocks.index') }}"> Back</a>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route('stocks.update',$stock->id) }}" method="POST">
        @csrf
        @method('PUT')

        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Product Name:</strong>
                    <input type="text" name="product_name" value="{{ $stock->product_name }}" class="form-control" placeholder="Product Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Product Description:</strong>
                    <textarea class="form-control" name="product_desc" style="height:150px"  placeholder="Product Description">{{ $stock->product_desc }}</textarea>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Qty:</strong>
                    <input type="number" name="product_qty" class="form-control" style="height:150px" value="{{ $stock->product_qty }}"  placeholder="Quantity">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>

    </form>
@endsection
Code language: HTML, XML (xml)

show.blade.php

@extends('stocks.layout')

@section('content')

    <div class="row">
        <div class="col-lg-12">
            <h2 class="text-center">Show Stock</h2>
        </div>
        <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;">
            <a class="btn btn-primary" href="{{ route('stocks.index') }}"> Back</a>
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Product Name : </strong>
                {{ $stock->product_name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Product Description : </strong>
                {{ $stock->product_desc }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Quantity : </strong>
                {{ $stock->product_qty }}
            </div>
        </div>
    </div>
@endsection
Code language: HTML, XML (xml)

Type the following command in your terminal to run the application.

php artisan serve

Hope this tutorial helps you! Feel free to drop your opinion at the comment section.

Categories
Laravel

CRUD in Laravel 5.8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 5.8. Laravel is one of the fastest growing frameworks for PHP built by Taylor Otwell.

# Laravel 5.8

Laravel 5.8 continues the improvements made in the previous release (version 5.7). ReferΒ release notesΒ to see the changes made in Laravel 5.8.

In this tutorial, You’ll learn the Basic CRUD operation in Laravel. Follow the step by step guide to create the CRUD application.

  1. Install Laravel

First, let install Laravel using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel students
Code language: PHP (php)
  1. Configure Database Details

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE='Your DB Name'
DB_USERNAME='Your DB UserName'
DB_PASSWORD='Your DB Password'
Code language: PHP (php)
  1. Create the migration file.

Go to the terminal and type the following php artisan command to generate the model and migration file.

php artisan make:migration create_students_table --create=students
Code language: PHP (php)

The migration will be created under “database/migrations“. Edit the file with the code below to create Students Table.

create_students_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('students');
}
}
Code language: Ceylon (ceylon)

Type the following command to run the migration.

php artisan migrate
  1. Create route, controller and model

In this step, Go to ‘routes->web.php’ file, add the following line of code.

//redirect to the students resource controller
Route::get('/', function () {
    return redirect('/students');
});

Route::resource('students','StudentController');
Code language: PHP (php)

Create the Student model using the following command.

php artisan make:model Student
Code language: PHP (php)

The model wil be generated in “app/Student.php” Now, we will write the schema inside Student.php file.

Student.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = [
        'name', 'detail'
    ];
}
Code language: PHP (php)

Create the StudentController as resource using the following command.

php artisan make:controller StudentController --resource --model=Student
Code language: PHP (php)

app/Http/Controllers/StudentController.php

<?php
namespace App\Http\Controllers;

use App\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{

    public function index()
    {
        $students = Student::latest()->paginate(5);
        return view('students.index',compact('students'))->with('i', (request()->input('page', 1) - 1) * 5);
    }

    public function create()
    {
        return view('students.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);

        Student::create($request->all());
        return redirect()->route('students.index')->with('success','Student created successfully.');
    }

    public function show(Student $student)
    {
        return view('students.show',compact('student'));
    }


    public function edit(Student $student)
    {
        return view('students.edit',compact('student'));
    }

    public function update(Request $request, Student $student)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);

        $student->update($request->all());
        return redirect()->route('students.index')->with('success','Student updated successfully.');
    }


    public function destroy(Student $student)
    {
        $student->delete();
        return redirect()->route('students.index')->with('success','Student deleted successfully.');
    }
}
Code language: PHP (php)
  1. Create the view Files

You need to create a folder Inside resources -> views as students. Inside that folder, create the following five files.

  1. layout.blade.php
  2. index.blade.php
  3. create.blade.php
  4. edit.blade.php
  5. show.blade.php

resources/views/students/layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 6.0,5.8 CRUD Application - bishrulhaq.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>

<div class="container">
    <div class="card" style="margin-top: 20px;">
        <div class="card-body">
        @yield('content')
        </div>
    </div>
</div>

</body>
</html>
Code language: HTML, XML (xml)

resources/views/students/index.blade.php

@extends('students.layout')

@section('content')

    <div class="row">
        <div class="col-lg-12">
            <h2 class="text-center">Simple Student Management CRUD Application</h2>
        </div>
        <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;">
            <a class="btn btn-success " href="{{ route('students.create') }}"> Add Student</a>
        </div>
    </div>

    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            {{ $message }}
        </div>
    @endif

    @if(sizeof($students) > 0)
        <table class="table table-bordered">
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Details</th>
                <th width="280px">More</th>
            </tr>
            @foreach ($students as $student)
                <tr>
                    <td>{{ ++$i }}</td>
                    <td>{{ $student->name }}</td>
                    <td>{{ $student->detail }}</td>
                    <td>
                        <form action="{{ route('students.destroy',$student->id) }}" method="POST">

                            <a class="btn btn-info" href="{{ route('students.show',$student->id) }}">Show</a>
                            <a class="btn btn-primary" href="{{ route('students.edit',$student->id) }}">Edit</a>

                            @csrf
                            @method('DELETE')

                            <button type="submit" class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </table>
    @else
        <div class="alert alert-alert">Start Adding to the Database.</div>
    @endif

    {!! $students->links() !!}

@endsection
Code language: HTML, XML (xml)

resources/views/students/create.blade.php

@extends('students.layout')

@section('content')

    <div class="row">
        <div class="col-lg-12">
            <h2 class="text-center">Add Student</h2>
        </div>
        <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;">
            <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Oops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route('students.store') }}" method="POST">
        @csrf

        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>

    </form>
@endsection
Code language: HTML, XML (xml)

resources/views/students/edit.blade.php

@extends('students.layout')

@section('content')

    <div class="row">
        <div class="col-lg-12">
            <h2 class="text-center">Edit Student</h2>
        </div>
        <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;">
            <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route('students.update',$student->id) }}" method="POST">
        @csrf
        @method('PUT')

        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" value="{{ $student->name }}" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $student->detail }}</textarea>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>

    </form>
@endsection
Code language: HTML, XML (xml)

resources/views/students/show.blade.php

@extends('students.layout')

@section('content')

    <div class="row">
        <div class="col-lg-12">
            <h2 class="text-center">Show Student</h2>
        </div>
        <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;">
            <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a>
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $student->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $student->detail }}
            </div>
        </div>
    </div>
@endsection
Code language: HTML, XML (xml)

Finally, Laravel CRUD Application is ready to run. Type the following command in your terminal to run the application.

php artisan serve
Code language: PHP (php)

Hope this tutorial helps you! Feel free to drop your opinion at the comment section.

Categories
JS

AJAX for Database Operations

This tutorial is created to implement CRUD operations via AJAX (Asynchronous JavaScript and XML). Ajax is used for rich-internet applications that emulate the responsiveness and complex user interfaces. It is a set of inter-related technologies like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest. It helps to send and receive data asynchronously without reloading the web page and it’s faster.

  1. Create the DB(Database)

Create the DB and run the following SQL query to create a table student inside the MySQL database.

SQL query to create a table named student

CREATE TABLE student (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    username varchar(255) NOT NULL,
    password varchar(255) NOT NULL
);
Code language: PHP (php)

Now, It’s time to create the DB config.php file as shown below

config.php

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', '');
define('DB_PASSWORD', '');
define('DB_NAME', 'ajax_application');

$link = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

if ($link->connect_errno) {
    printf("Connect failed: %s\n", $link->connect_error);
    exit();
}
Code language: HTML, XML (xml)
  1. Creating the Pages

You need to create the following files to run the Ajax CRUD application

  1. index.php
  2. add.php
  3. delete.php
  4. edit.php
  5. update.php

index.php

<!DOCTYPE html>
<html>
<head>
    <title>AJAX for Database Operations | bishrulhaq.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 20px;">
    <div class="card">
        <div class="card-body">
            <h1 class="text-center">AJAX for Database Operations</h1>

        </div>
    </div>
</div>
<div class="container" style="margin-top: 25px;">
    <div class="row">
        <div class="col-12">
            <div class="text-center">
                <h5>Add New Record</h5>
            </div>
            <div class="form-inline" style="margin-bottom: 25px;">
                <div class="form-group col-3">
                    <input type="text" name="name" id="name" placeholder="Name" class="form-control"/>
                </div>
                <div class="form-group col-3">
                    <input type="text" name="username" id="username" placeholder="Username" class="form-control"/>
                </div>
                <div class="form-group col-3">
                    <input type="text" id="password" name="password" placeholder="Password" class="form-control"
                           required/>
                </div>
                <div class="form-group col-3">
                    <button type="button" class="btn btn-primary" id="add" name="add" onclick="addRecord()">Add Record
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div id="link-edit">

            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div id="records_content"></div>
            <div class="col-12" id="table_content">
            </div>
        </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>

    $(document).ready(function () {

        $.get("view.php", function (data) {
            $("#table_content").html(data);
        });
    });

    function addRecord() {

        var name = $('#name').val();
        var username = $('#username').val();
        var password = $('#password').val();

        $.ajax({
            url: "add.php",
            type: "POST",
            data: {name: name, username: username, password: password},
            success: function (data, status, xhr) {
                $('#name').val('');
                $('#username').val('');
                $('#password').val('');
                $.get("view.php", function (html) {
                    $("#table_content").html(html);
                });
                $('#records_content').fadeOut(1100).html(data);
            },
            error: function () {
                $('#records_content').fadeIn(3000).html('<div class="text-center">Error!</div>');
            },
            beforeSend: function () {
                $('#records_content').fadeOut(700).html('<div class="text-center">Loading...</div>');
            }
        });
    }

</script>
</body>
</html>
Code language: HTML, XML (xml)

In this step, Let’s create the “add.php” and add the following code inside it.

add.php

<?php
require_once('config.php');

$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];

if (!empty($name) && !empty($username) && !empty($password)) {
    $query = $con->prepare("INSERT into student (name, username, password) VALUES (?,?,?)");

    $query->bind_param('sss', $name, $username, $password);

    $result = $query->execute();

    if ($result) {
        echo '1 Record Added!';
    } else {
        exit(mysqli_error($con));
    }

}
Code language: HTML, XML (xml)

Create “delete.php” and add the following code inside it. Which will help to delete particular user by passing the ID.

delete.php

<?php
require_once('config.php');

$id = $_POST['id'];

if (empty($id)) {
    echo 'Error!';
}
$query = $con->prepare("DELETE FROM student where id= ?");

$query->bind_param('i', $id);

$result = $query->execute();

if ($result) {
    echo '1 Record Deleted!';
} else {
    exit(mysqli_error($con));
}
Code language: HTML, XML (xml)

Now, Let’s Create the “edit.php” and add the following code inside it.

<?php

require_once('config.php');
$id = $_POST['id'];

if (empty($id)) { ?>
    <div class="text-center">No records found under this selection <a href="#" onclick="$('#link-add').hide();$('#show-add').show(700);">Hidethis</a></div>
    <?php die();
}

$query = "SELECT * FROM student where id = ?";
if ($stmt = $con->prepare($query)) {
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
    ?>
    <div class="form-inline" id="edit-data" style="margin-bottom: 20px;">
        <div class="form-group col-3">
            <input type="text" name="student_name" id="student_name" value="<?php echo $row['name']; ?>"
                   placeholder="Name" class="form-control" required/>
        </div>
        <div class="form-group col-3">
            <input type="text" name="student_username" id="student_username" placeholder="Username" class="form-control"
                   value="<?php echo $row['username']; ?>" required/>
        </div>
        <div class="form-group col-3">
            <input type="text" id="student_password" name="student_password" placeholder="Password" class="form-control"
                   value="<?php echo $row['password']; ?>" required/>
        </div>
        <div class="form-group col-3">
            <button type="button" class="btn btn-primary update" id="<?php echo $row['id']; ?>" name="update"
                    onclick="updateRecord(<?php echo $row['id']; ?>)">Update Record
            </button>
            <button type="button" href="javascript:void(0);" class="btn btn-default" id="cancel"
                    onclick="$('#link-edit').slideUp(400);$('#show-add').show(700);">Cancel
            </button>
        </div>
    </div>
<?php }}}} ?>

<script type="text/javascript">
    function updateRecord(student_id) {

        var id = student_id;
        var name = $('#student_name').val();
        var username = $('#student_username').val();
        var password = $('#student_password').val();

        $.ajax({
            url: "update.php",
            type: "POST",
            data: {id: id, name: name, username: username, password: password},
            success: function (data, status, xhr) {
                $('#name').val('');
                $('#username').val('');
                $('#password').val('');
                $('#records_content').fadeOut(1100).html(data);
                $.get("view.php", function (html) {
                    $("#table_content").html(html);
                });
                $('#records_content').fadeOut(1100).html(data);
            },
            complete: function () {
                $('#link-edit').hide();
                $('#show-add').show(700);
            }
        });
    }
</script>
Code language: HTML, XML (xml)

Create “update.php” and add the following code inside it. Which will help to update the particular user data

update.php

<?php
require_once('config.php');

$id = $_POST['id'];
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];

if (!empty($name) && !empty($username) && !empty($password) && !empty($id)) {
    $query = "UPDATE student SET name = ?, username = ?, password = ? WHERE id = ?";
    if ($stmt = $con->prepare($query)) {
        $stmt->bind_param("sssi", $name, $username, $password, $id);
        $stmt->execute();
        if ($stmt->error) {
            echo '' . $stmt->error . '';
        } else {
            echo '1 Record updated!';

        }
    }
} else {
    echo 'error while updating record';
}
Code language: HTML, XML (xml)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.