crud ajax php mysql

CRUD PHP MYSQL AJAX BOOTSTRAP DOWNLOAD

In this article you would be learning PHP CRUD with AJAX from scratch.you can download or copy paste the source code for free and its easy to understand and modify.Normally CRUD comes in almost all the php projects.For example making an admin panel,where admin can do insert, update and delete operations.

What is CRUD?

CRUD stands for CREATE READ UPDATE AND DELETE

What is AJAX?

It is the technique for creating dynamic web pages.That's means updating web page without page reload.

Below is the screenshots of the CRUD PHP MYSQL AJAX BOOTSTRAP project
crud ajax php mysql
php ajax crud tutorial

In this php ajax crud tutorial,you would be learning the followings

  • Inserting an image to database without page reload.
  • Updating an image from database without page reload.
  • deleting an image form database without page reload.
  • Bootstrap modal popup on onclicking action buttons.
  • Fetching the image from the database to the front-end without creating extra image folder in the root folder.

How to upload image in php mysqli database and display ?

To store images on mysql database,there are four types of image datatypes.

  • "BLOB and Tiny BLOB" - Are used to store small sized images.
  • "Medium BLOB" - Is used to store medium sized images.
  • "Long BLOB" - Is used to store large sized images.

Requirements for this project.

  • Basics of HTML
  • Basics of CSS
  • Basics of Javascript(AJAX)

  • Basics of Jquery
  • Basics of bootstrap
  • Localhost Server (Xamp or wamp)

Additionally we will be using , Its a great library for front-end developer

How many pages for this project?

The project will be of only two pages say "index.php and action.php"

"index.php",
-----This file contains some jquey code which makes some operation request to "action.php" file.

"action.php",
-----This file contains some php and sql ,due to which we can insert , update and delete images.

Firstly, Create a database with name "crud"

Secondly, Create table with name "t_images" and the table should contain following columns

  • "id" : as auto increment which defines each row unique with datatype int(11)
  • "name" : contains the inserted/updated images with datatype LONGBLOB
OR

Run the following sql query in the "crud" database.


                CREATE TABLE IF NOT EXISTS `t_images` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `name` longblob NOT NULL,
            PRIMARY KEY(id)
          ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

          
        

After running the above query a table will be created in the "crud" database.

index.php

    <!DOCTYPE html>
    <html>
     <head>
      <title>CRUD PHP MYSQL AJAX BOOTSTRAP DOWNLOAD-without page reload</title>
      <!-- JQuery -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <!-- Bootstrap tooltips -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <!-- MDB core JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.7/js/mdb.min.js"></script>
      <!-- Font Awesome -->
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
      <!-- Bootstrap core CSS -->
      <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
      <!-- Material Design Bootstrap -->
      <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.7/css/mdb.min.css" rel="stylesheet">
     </head>
     <!--Main Navigation-->
    <header>
      <!--Navbar-->
      <nav class="navbar navbar-expand-lg navbar-dark primary-color">

        <!-- Navbar brand -->
        <a class="navbar-brand" href="#">Navbar</a>

        <!-- Collapse button -->
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#basicExampleNav" aria-controls="basicExampleNav"
            aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <!-- Collapsible content -->
        <div class="collapse navbar-collapse" id="basicExampleNav">

            <!-- Links -->
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home
                        <span class="sr-only">(current)</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Features</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Pricing</a>
                </li>

                <!-- Dropdown -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
                    <div class="dropdown-menu dropdown-primary" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" href="#">Action</a>
                        <a class="dropdown-item" href="#">Another action</a>
                        <a class="dropdown-item" href="#">Something else here</a>
                    </div>
                </li>

            </ul>
            <!-- Links -->

            <form class="form-inline">
                <div class="md-form my-0">
                    <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
                </div>
            </form>
        </div>
        <!-- Collapsible content -->

      </nav>
      <!--/.Navbar-->

    </header>

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

        <button type="button" name="add" id="add" class="btn btn-success mb-5">Add Image</button>

       <div id="images">

       </div>
       <div id="imageModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
         <div class="modal-content">
          <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal">×</button>

          </div>
          <div class="modal-body">
           <form id="image_form" method="post" enctype="multipart/form-data">
            <p><label>Select Image</label>
            <input type="file" name="image" id="image" /></p><br />
            <input type="hidden" name="action" id="action" value="insert" /><!-- holds the insert string-->
            <input type="hidden" name="image_id" id="image_id" /><!-- holds the image id to update-->
            <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />

           </form>
          </div>
          <div class="modal-footer">
           <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
         </div>
        </div>
       </div>
      </div>
    </div>
    </div>
      <script>
      $(document).ready(function(){

       fetch_image();

       function fetch_image()
       {
        var action = "fetch";
        $.ajax({
         url:"action.php",
         method:"POST",
         data:{action:action},
         success:function(data)
         {
          $('#images').html(data);//displaying the entire table
         }
        })
       }
       $('#add').click(function(){
        $('#imageModal').modal('show');
        $('#image_form')[0].reset();
        $('.modal-title').text("Add Image");
        $('#image_id').val('');
        $('#action').val('insert');

       });
       $('#image_form').submit(function(event){
        event.preventDefault();
        var image_name = $('#image').val();
        if(image_name == '')
        {
         alert("Please Select Image");
         return false;
        }
        else
        {
         var extension = $('#image').val().split('.').pop().toLowerCase();
         if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
         {
          alert("Invalid Image File");
          $('#image').val('');
          return false;
         }
         else
         {
          $.ajax({
           url:"action.php",
           method:"POST",
           data:new FormData(this),
           contentType:false,
           processData:false,
           success:function(data)
           {
            alert(data);
            fetch_data();
            $('#image_form')[0].reset();
            $('#imageModal').modal('hide');
           }
          });
         }
        }
       });
       $(document).on('click', '.update', function(){
        $('#image_id').val($(this).attr("id"));
        $('#action').val("update");
        $('.modal-title').text("Update Image");

        $('#imageModal').modal("show");
       });
       $(document).on('click', '.delete', function(){
        var image_id = $(this).attr("id");
        var action = "delete";
        if(confirm("Are you sure you want to remove this image from database?"))
        {
         $.ajax({
          url:"action.php",
          method:"POST",
          data:{image_id:image_id, action:action},
          success:function(data)
          {
           alert(data);
           fetch_data();
          }
         })
        }
        else
        {
         return false;
        }
       });
      });
      </script>

      </main>
      </html>

    
  
action.php


      <?php
      if(isset($_POST["action"]))
      {
       $connect = mysqli_connect("localhost", "root", "", "crud");
       if($_POST["action"] == "fetch")
       {
        $query = "SELECT * FROM t_images ORDER BY id DESC";
        $result = mysqli_query($connect, $query);
        $output = '
         <table class="table table-bordered table-striped">
          <tr>
           <th width="10%">ID</th>
           <th width="60%">IMAGE</th>
           <th width="15%">UPDATE</th>
           <th width="15%">DELETE</th>
          </tr>
        ';
        while($row = mysqli_fetch_array($result))
        {
         $output .= '

          <tr>
           <td>'.$row["id"].'</td>
           <td>
            <img src="data:image/jpeg;base64,'.base64_encode($row['name'] ).'" height="60" width="75" class="img-thumbnail" />
           </td>
           <td><button type="button" name="update" class="btn btn-warning bt-xs update" id="'.$row["id"].'">Change</button></td>
           <td><button type="button" name="delete" class="btn btn-danger bt-xs delete" id="'.$row["id"].'">Remove</button></td>
          </tr>
         ';
        }
        $output .= '</table>';
        echo $output;
       }

       if($_POST["action"] == "insert")
       {
        $file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
        $query = "INSERT INTO t_images(name) VALUES ('$file')";
        if(mysqli_query($connect, $query))
        {
         echo 'Image Inserted into Database';
        }
       }
       if($_POST["action"] == "update")
       {
        $file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
        $query = "UPDATE t_images SET name = '$file' WHERE id = '".$_POST["image_id"]."'";
        if(mysqli_query($connect, $query))
        {
         echo 'Image Updated into Database';
        }
       }
       if($_POST["action"] == "delete")
       {
        $query = "DELETE FROM t_images WHERE id = '".$_POST["image_id"]."'";
        if(mysqli_query($connect, $query))
        {
         echo 'Image Deleted from Database';
        }
       }
      }
      ?>

    
  

This is the end of the php myql crud session.I hope it has helped you.

About author
Supreet Patil
I am a web developer.I have started the journey of web development 2017.I am CSE degree holder.
E-mail:psupreet12@gmail.com
Leave a reply