PHP 8 Image Upload CRUD Using Ajax Example

PHP 8 Image Upload CRUD Using Ajax Example

Hello dev, Today we are going to learn PHP 8 Image Upload CRUD Using Ajax Example. This tutorial will cover on CRUD how to upload image using ajax with example.

I am going to explain you PHP Image Upload CRUD Using Ajax Example. You will learn AJAX Image and File Upload in PHP with jQuery. This article will give you simple example of Ajax Image Upload using PHP and jQuery. We will use Ajax Image Upload with Form Data using jQuery, PHP and MySQL. I will give you simple Example of Image Upload with AJAX, PHP, and MYSQL.

Steps for PHP 8 Image Upload CRUD Using Ajax Example:

  • Step 1: File Structures
  • Step 2: Create Database and Table
  • Step 3: Create DB PHP File
  • Step 4: Create Function PHP File
  • Step 5: Create Index PHP File
  • Step 6: Create Fetch PHP File
  • Step 7: Create Fetch Single PHP File
  • Step 8: Create Insert PHP File
  • Step 9: Create Delete PHP File
  • Step 10: Testing
  • Step 11: Conclusion

Also Read: PHP 8 MySQL Ajax Pagination Example Tutorial

Step 1: File Structures

Before jump into the tutorial first we are going to see the file structures of our project. You can see the project file structures in the below image.

File Structures
File Structures

Step 2: Create Database and Table

Firstly we are going to create a database. To create a database open phpmyadmin and create a new database with name “image_upload_ajax” (you can give whatever name you want to).

Creating Database
Creating Database

Also Read: PHP 8 Multiple File Upload using Ajax Example Tutorial

Now its time to create a users table. To create a users table run the following query in database.

CREATE TABLE users(
    id INT AUTO_INCREMENT NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    image VARCHAR(50) NOT NULL,
    primary key (id)
);
Creating Users table
Creating Users table

Step 3: Create DB PHP File

Now we are going to create database connection db.php file inside a project folder and enter the following code inside it.

image_upload_ajax/db.php

<?php
    $username = 'root';
    $password = '';
    $connection = new PDO( 'mysql:host=localhost;dbname=image_upload_ajax', $username, $password );
?>

Please make changes accordingly to your database details.

Also Read: PHP Registration Form with Mobile OTP Verification Example

Step 4: Create Function PHP File

Now we are going to create our function.php in our project folder and enter the following code inside it.

image_upload_ajax/function.php

<?php

function upload_image()
{
    if(isset($_FILES["user_image"]))
    {
        $extension = explode('.', $_FILES['user_image']['name']);
        $new_name = rand() . '.' . $extension[1];
        $destination = './upload/' . $new_name;
        move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
        return $new_name;
    }
}

function get_image_name($user_id)
{
    include('db.php');
    $statement = $connection->prepare("SELECT image FROM users WHERE id = '$user_id'");
    $statement->execute();
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
        return $row["image"];
    }
}

function get_total_all_records()
{
    include('db.php');
    $statement = $connection->prepare("SELECT * FROM users");
    $statement->execute();
    $result = $statement->fetchAll();
    return $statement->rowCount();
}

?>

Step 5: Create Index PHP File

Create a index.php file inside our project folder and enter the following code inside it.

image_upload_ajax/index.php

<html>
    <head>
        <title>PHP 8 Image Upload CRUD Using Ajax Example - LaravelTuts.com</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs5/dt-1.11.5/datatables.min.css"/>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/v/bs5/dt-1.11.5/datatables.min.js"></script>
        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <style>
        </style>
    </head>
    <body class="bg-dark">
        <div class="container mt-5 pt-3">
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-11">
                            <h1>PHP 8 Image Upload CRUD Using Ajax Example - LaravelTuts.com</h1>
                        </div>
                        <div class="col-md-1 text-end">
                            <button type="button" id="add_button" data-bs-toggle="modal" data-bs-target="#userModal" class="btn btn-success btn-lg m-1"><i class="fa fa-plus-square-o" aria-hidden="true"></i></button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                        <table id="user_data" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th width="10%">Image</th>
                                    <th width="35%">First Name</th>
                                    <th width="35%">Last Name</th>
                                    <th width="10%">Edit</th>
                                    <th width="10%">Delete</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>
<div id="userModal" class="modal fade">
    <div class="modal-dialog">
        <form method="post" id="user_form" enctype="multipart/form-data">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Add User</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div>
                        <label>Enter First Name</label>
                        <input type="text" name="first_name" id="first_name" class="form-control"/>                     
                    </div>
                    
                    <div>
                        <label>Enter Last Name</label>
                        <input type="text" name="last_name" id="last_name" class="form-control"/>
                    </div>
                    
                    <div>
                        <label>Select User Image</label>
                        <input type="file" name="user_image" id="user_image" class="form-control">
                        <span id="user_uploaded_image"></span>  
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="user_id" id="user_id" />
                    <input type="hidden" name="operation" id="operation" />
                    <input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
                    <button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    $('#add_button').click(function(){
        $('#user_form')[0].reset();
        $('.modal-title').text("Add User");
        $('#action').val("Add");
        $('#operation').val("Add");
        $('#user_uploaded_image').html('');
    });
    
    var dataTable = $('#user_data').DataTable({
        "processing":true,
        "serverSide":true,
        "order":[],
        "ajax":{
            url:"fetch.php",
            type:"POST"
        },
        "columnDefs":[
            {
                "targets":[0, 3, 4],
                "orderable":false,
            },
        ],
    });
    $(document).on('submit', '#user_form', function(event){
        event.preventDefault();
        var firstName = $('#first_name').val();
        var lastName = $('#last_name').val();
        var extension = $('#user_image').val().split('.').pop().toLowerCase();
        if(extension != '')
        {
            if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
            {
                alert("Invalid Image File");
                $('#user_image').val('');
                return false;
            }
        }   
        if(firstName != '' && lastName != '')
        {
            $.ajax({
                url:"insert.php",
                method:'POST',
                data:new FormData(this),
                contentType:false,
                processData:false,
                success:function(data)
                {
                    alert(data);
                    $('#user_form')[0].reset();
                    $('#userModal').modal('hide');
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            alert("Both Fields are Required");
        }
    });
    
    $(document).on('click', '.update', function(){
        var user_id = $(this).attr("id");
        $.ajax({
            url:"fetch_single.php",
            method:"POST",
            data:{user_id:user_id},
            dataType:"json",
            success:function(data)
            {
                $('#userModal').modal('show');
                $('#first_name').val(data.first_name);
                $('#last_name').val(data.last_name);
                $('.modal-title').text("Edit User");
                $('#user_id').val(user_id);
                $('#user_uploaded_image').html(data.user_image);
                $('#action').val("Edit");
                $('#operation').val("Edit");
            }
        })
    });
    
    $(document).on('click', '.delete', function(){
        var user_id = $(this).attr("id");
        if(confirm("Are you sure you want to delete this?"))
        {
            $.ajax({
                url:"delete.php",
                method:"POST",
                data:{user_id:user_id},
                success:function(data)
                {
                    alert(data);
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            return false;   
        }
    });
});
</script>

Also Read: How to Remove a Specific Element From an Array in PHP

Step 6: Create Fetch PHP File

Same as index file, create a fetch.php file inside our project folder and enter the following code inside it.

image_upload_ajax/fetch.php

<?php
    include('db.php');
    include('function.php');

    $query = '';
    $output = array();
    $query .= "SELECT * FROM users";

    if(isset($_POST["search"]["value"]))
    {
        $query .= ' where first_name LIKE "%'.$_POST["search"]["value"].'%" ';
        $query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'%" ';
    }
    if(isset($_POST["order"]))
    {
        $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
    }
    else
    {
        $query .= 'ORDER BY id DESC ';
    }
    if($_POST["length"] != -1)
    {
        $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
    }


    $statement = $connection->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $data = array();
    $filtered_rows = $statement->rowCount();
    foreach($result as $row)
    {
        $image = '';
        if($row["image"] != '')
        {
            $image = '<img src="upload/'.$row["image"].'" class="img-thumbnail" width="100" height="35" />';
        }
        else
        {
            $image = '';
        }
        $sub_array = array();
        $sub_array[] = $image;
        $sub_array[] = $row["first_name"];
        $sub_array[] = $row["last_name"];
        $sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-primary btn-xs update mx-4"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button>';
        $sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete mx-4"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
        $data[] = $sub_array;
    }
    $output = array(
        "draw"              =>  intval($_POST["draw"]),
        "recordsTotal"      =>  $filtered_rows,
        "recordsFiltered"   =>  get_total_all_records(),
        "data"              =>  $data
    );

    echo json_encode($output);

?>

Step 7: Create Fetch Single PHP File

Now, create a fetch_single.php file inside our project folder and enter the following code inside it.

image_upload_ajax/fetch_single.php

<?php
    include('db.php');
    include('function.php');
    if(isset($_POST["user_id"]))
    {
        $output = array();
        $statement = $connection->prepare(
            "SELECT * FROM users 
            WHERE id = '".$_POST["user_id"]."' 
            LIMIT 1"
        );
        $statement->execute();
        $result = $statement->fetchAll();
        foreach($result as $row)
        {
            $output["first_name"] = $row["first_name"];
            $output["last_name"] = $row["last_name"];
            if($row["image"] != '')
            {
                $output['user_image'] = '<img src="upload/'.$row["image"].'" class="img-thumbnail" width="50" height="35" /><input type="hidden" name="hidden_user_image" value="'.$row["image"].'" />';
            }
            else
            {
                $output['user_image'] = '<input type="hidden" name="hidden_user_image" value="" />';
            }
        }
        echo json_encode($output);
    }
?>

Also Read: Upload Images to Server PHP Tutorial (2022)

Step 8: Create Insert PHP File

Create a insert.php file inside our project folder and enter the following code inside it.

image_upload_ajax/insert.php

<?php
    include('db.php');
    include('function.php');
    if(isset($_POST["operation"]))
    {
        if($_POST["operation"] == "Add")
        {
            $image = '';
            if($_FILES["user_image"]["name"] != '')
            {
                $image = upload_image();
            }
            $statement = $connection->prepare("
                INSERT INTO users (first_name, last_name, image) 
                VALUES (:first_name, :last_name, :image)
            ");
            $result = $statement->execute(
                array(
                    ':first_name'   =>  $_POST["first_name"],
                    ':last_name'    =>  $_POST["last_name"],
                    ':image'        =>  $image
                )
            );
            if(!empty($result))
            {
                echo 'Data Inserted';
            }
        }
        if($_POST["operation"] == "Edit")
        {
            $image = '';
            if($_FILES["user_image"]["name"] != '')
            {
                $image = upload_image();
            }
            else
            {
                $image = $_POST["hidden_user_image"];
            }
            $statement = $connection->prepare(
                "UPDATE users 
                SET first_name = :first_name, last_name = :last_name, image = :image  
                WHERE id = :id
                "
            );
            $result = $statement->execute(
                array(
                    ':first_name'   =>  $_POST["first_name"],
                    ':last_name'    =>  $_POST["last_name"],
                    ':image'        =>  $image,
                    ':id'           =>  $_POST["user_id"]
                )
            );
            if(!empty($result))
            {
                echo 'Data Updated';
            }
        }
    }
?>

Step 9: Create Delete PHP File

At last, Create a delete.php file inside our project folder and enter the following code inside it.

image_upload_ajax/delete.php

<?php
    include('db.php');
    include("function.php");
    if(isset($_POST["user_id"]))
    {
        $image = get_image_name($_POST["user_id"]);
        if($image != '')
        {
            unlink("upload/" . $image);
        }
        $statement = $connection->prepare(
            "DELETE FROM users WHERE id = :id"
        );
        $result = $statement->execute(
            array(
                ':id'   =>  $_POST["user_id"]
            )
        );
        
        if(!empty($result))
        {
            echo 'Data Deleted';
        }
    }
?>

Note: Before testing the application make sure to create a upload folder inside your project directory to upload a images inside it.

Also Read: Integration PayPal Payment Gateway in PHP

Step 10: Testing

Now, Everything is ready, we are going to test our application. Open any web browser and open the following link.

http://localhost/image_upload_ajax/

Note: Change the folder name if you had a different name.

Previews:

Lists - PHP 8 Image Upload CRUD Using Ajax Example
Lists – PHP 8 Image Upload CRUD Using Ajax Example
Add - PHP 8 Image Upload CRUD Using Ajax Example
Add – PHP 8 Image Upload CRUD Using Ajax Example
Edit - PHP 8 Image Upload CRUD Using Ajax Example
Edit – PHP 8 Image Upload CRUD Using Ajax
Delete - PHP 8 Image Upload CRUD Using Ajax Example
Delete – PHP 8 Image Upload CRUD Using Ajax

Step 11: Conclusion

Today, We had learn PHP 8 Image Upload CRUD Using Ajax Example. Hope this tutorial helped you with learning PHP. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Drag & Drop Reorder Images in PHP (2022)

Source Code

Get the full source code for just $5. This is because for making our website running!

[wp_express_checkout product_id=”1030″]

I am Nitin Pujari, a full-stack developer and . I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, Php, Codeigniter, React, Angular, Vue, and Laravel.

Leave a Reply