Skip to main content

PHP Ajax Mysql CRUD App with upload, select, radio and checkbox fields.


 Code:index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CRUD PHP MySQL AJAX</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2>CRUD with Image Upload, Select, Radio, Checkbox</h2>

        <!-- Form to Create/Update User -->
        <form id="userForm" enctype="multipart/form-data">
            <input type="hidden" name="id" id="id">
            <div class="form-group">
                <label>Name:</label>
                <input type="text" class="form-control" name="name" id="name" required>
            </div>
            <div class="form-group">
                <label>Email:</label>
                <input type="email" class="form-control" name="email" id="email" required>
            </div>
            <div class="form-group">
                <label>Gender:</label><br>
                <input type="radio" name="gender" value="Male" checked> Male
                <input type="radio" name="gender" value="Female"> Female
            </div>
            <div class="form-group">
                <label>Skills:</label><br>
                <input type="checkbox" name="skills[]" value="HTML"> HTML
                <input type="checkbox" name="skills[]" value="CSS"> CSS
                <input type="checkbox" name="skills[]" value="JavaScript"> JavaScript
                <input type="checkbox" name="skills[]" value="PHP"> PHP
            </div>
            <div class="form-group">
                <label>Country:</label>
                <select class="form-control" name="country" id="country">
                    <option value="USA">USA</option>
                    <option value="Canada">Canada</option>
                    <option value="UK">UK</option>
                </select>
            </div>
            <div class="form-group">
                <label>Profile Picture:</label>
                <input type="file" class="form-control" name="profile_pic" id="profile_pic">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>

        <!-- Response Div -->
        <div id="response" class="mt-3"></div>
       
        <!-- User Data Display -->
        <div id="userData" class="mt-3"></div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function() {
            // Load Users on Page Load
            loadUsers();

            // Submit Form via AJAX
            $('#userForm').on('submit', function(e) {
                e.preventDefault();
                var formData = new FormData(this);
                var action = $('#id').val() ? 'update' : 'create';
                formData.append('action', action);

                $.ajax({
                    url: 'process.php',
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        $('#response').html(response);
                        $('#userForm')[0].reset();
                        loadUsers();
                    }
                });
            });

            // Load Users
            function loadUsers() {
                $.ajax({
                    url: 'process.php',
                    type: 'POST',
                    data: {action: 'read'},
                    success: function(response) {
                        $('#userData').html(response);
                    }
                });
            }

            // Edit User
            $(document).on('click', '.edit-btn', function() {
                var id = $(this).data('id');
                $.ajax({
                    url: 'process.php',
                    type: 'POST',
                    data: {action: 'get_user', id: id},
                    success: function(response) {
                        var user = JSON.parse(response);
                        $('#id').val(user.id);
                        $('#name').val(user.name);
                        $('#email').val(user.email);
                        $('input[name="gender"][value="' + user.gender + '"]').prop('checked', true);
                        $('#country').val(user.country);
                        $('input[name="skills[]"]').each(function() {
                            $(this).prop('checked', user.skills.split(',').includes($(this).val()));
                        });
                    }
                });
            });

            // Delete User
            $(document).on('click', '.delete-btn', function() {
                var id = $(this).data('id');
                if (confirm('Are you sure you want to delete this user?')) {
                    $.ajax({
                        url: 'process.php',
                        type: 'POST',
                        data: {action: 'delete', id: id},
                        success: function(response) {
                            $('#response').html(response);
                            loadUsers();
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>



Code: process.php

<?php

// Database connection

$host = 'localhost';

$dbname = 'crud_example';

$username = 'root';

$password = '';


try {

    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

    die("Connection failed: " . $e->getMessage());

}


// Create User

if ($_POST['action'] == 'create') {

    $name = $_POST['name'];

    $email = $_POST['email'];

    $gender = $_POST['gender'];

    $country = $_POST['country'];

    $skills = isset($_POST['skills']) ? implode(',', $_POST['skills']) : '';


    // Handle Image Upload

    $profile_pic = '';

    if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] == 0) {

        $profile_pic = 'uploads/' . time() . '_' . $_FILES['profile_pic']['name'];

        move_uploaded_file($_FILES['profile_pic']['tmp_name'], $profile_pic);

    }


    $sql = "INSERT INTO users (name, email, gender, skills, profile_pic, country) 

            VALUES (:name, :email, :gender, :skills, :profile_pic, :country)";

    $stmt = $pdo->prepare($sql);

    $stmt->execute([

        ':name' => $name,

        ':email' => $email,

        ':gender' => $gender,

        ':skills' => $skills,

        ':profile_pic' => $profile_pic,

        ':country' => $country

    ]);


    echo "User created successfully!";

}


// Read Users

if ($_POST['action'] == 'read') {

    $stmt = $pdo->query("SELECT * FROM users ORDER BY created_at DESC");

    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);


    $output = '';

    foreach ($users as $user) {

        $output .= "<div class='user'>

                        <img src='{$user['profile_pic']}' width='100'><br>

                        Name: {$user['name']}<br>

                        Email: {$user['email']}<br>

                        Gender: {$user['gender']}<br>

                        Skills: {$user['skills']}<br>

                        Country: {$user['country']}<br>

                        <button class='edit-btn btn btn-warning' data-id='{$user['id']}'>Edit</button>

                        <button class='delete-btn btn btn-danger' data-id='{$user['id']}'>Delete</button>

                    </div><hr>";

    }

    echo $output;

}


// Get User for Edit

if ($_POST['action'] == 'get_user') {

    $id = $_POST['id'];

    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");

    $stmt->execute([':id' => $id]);

    $user = $stmt->fetch(PDO::FETCH_ASSOC);


    echo json_encode($user);

}



?>


<?php


// Update User

if ($_POST['action'] == 'update') {

    $id = $_POST['id'];

    $name = $_POST['name'];

    $email = $_POST['email'];

    $gender = $_POST['gender'];

    $country = $_POST['country'];

    $skills = isset($_POST['skills']) ? implode(',', $_POST['skills']) : '';


    // Handle Image Upload (if a new file is uploaded)

    $profile_pic = '';

    if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] == 0) {

        // Upload new image

        $profile_pic = 'uploads/' . time() . '_' . $_FILES['profile_pic']['name'];

        move_uploaded_file($_FILES['profile_pic']['tmp_name'], $profile_pic);

    } else {

        // If no new file is uploaded, keep the existing profile picture

        $stmt = $pdo->prepare("SELECT profile_pic FROM users WHERE id = :id");

        $stmt->execute([':id' => $id]);

        $user = $stmt->fetch();

        $profile_pic = $user['profile_pic'];

    }


    // SQL query to update user details

    $sql = "UPDATE users 

            SET name = :name, email = :email, gender = :gender, skills = :skills, profile_pic = :profile_pic, country = :country 

            WHERE id = :id";

    $stmt = $pdo->prepare($sql);

    $stmt->execute([

        ':name' => $name,

        ':email' => $email,

        ':gender' => $gender,

        ':skills' => $skills,

        ':profile_pic' => $profile_pic,

        ':country' => $country,

        ':id' => $id

    ]);


    echo "User updated successfully!";

}



// Delete User

if ($_POST['action'] == 'delete') {

    $id = $_POST['id'];

    

    // Delete the user's profile picture from the server (optional)

    $stmt = $pdo->prepare("SELECT profile_pic FROM users WHERE id = :id");

    $stmt->execute([':id' => $id]);

    $user = $stmt->fetch();

    if (file_exists($user['profile_pic'])) {

        unlink($user['profile_pic']); // Delete the image file

    }


    // SQL query to delete the user

    $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");

    $stmt->execute([':id' => $id]);


    echo "User deleted successfully!";

}


?>

Database structure;


-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 19, 2024 at 06:27 PM
-- Server version: 10.4.32-MariaDB
-- PHP Version: 8.2.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `crud_example`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `gender` varchar(100) NOT NULL,
  `skills` varchar(250) NOT NULL,
  `country` varchar(100) NOT NULL,
  `profile_pic` varchar(250) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email`, `gender`, `skills`, `country`, `profile_pic`, `created_at`) VALUES
(1, 'sadiya', 'sadiya333@gmail.com', 'Female', 'HTML,CSS,JavaScript', 'USA', 'uploads/1732037244_TECHNOKING (1).jpg', '2024-11-19 17:25:06');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `name` (`name`),
  ADD UNIQUE KEY `emai` (`email`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


Download  Source Code:

Download


Comments

Popular posts from this blog

Microsoft Excel top functions.

  Microsoft Excel offers numerous functions to simplify data analysis and calculation. Here are some of the most commonly used and powerful functions: Basic Functions SUM : Adds values. =SUM(A1:A10) AVERAGE : Calculates the mean of numbers. =AVERAGE(A1:A10) IF : Performs logical tests and returns values based on conditions. =IF(A1>10, "Yes", "No") COUNT : Counts numeric values in a range. =COUNT(A1:A10) LEN : Returns the length of a text string. =LEN(A1) Lookup and Reference Functions VLOOKUP : Looks for a value in the first column and returns a value in the same row from another column. =VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup]) HLOOKUP : Similar to Here are practical examples of common Excel functions and how they can be applied in real-life scenarios: 1. SUM Scenario: Calculate the total sales for a week. Example: A B Day Sales Monday 200 Tuesday 150 Wednesday 300 Thursday 250 Friday 100 ...

Creating Wages Sheet using Microsoft Excel

  Creating wages sheet using Microsoft Excel The DAYS360 function in Microsoft Excel calculates the number of days between two dates based on a 360-day year (commonly used in financial calculations). A 360-day year assumes each month has 30 days, simplifying interest and payment schedules. Syntax: DAYS360(start_date, end_date, [method]) Parameters: start_date : The starting date (required). Enter it as a valid date or reference a cell containing a date. end_date : The ending date (required). Enter it similarly to the start_date. method : Logical value (optional). FALSE (default): Uses the U.S. (NASD) method for date calculations. TRUE : Uses the European method. Key Differences Between Methods: U.S. (NASD) : Adjusts the start and end dates depending on whether they fall on the 31st of a month. European : Always treats the start and end dates as the 30th of the month if they are the 31st. Example Usage: Example 1: Calculate days using the U.S. method =DAYS360("01/01/2024", ...

How to use Microsoft Excel PMT function?

  To use the PMT function in Microsoft Excel, follow these steps: Steps to Use the PMT Function: Open Excel : Open your Excel workbook where you want to calculate the payment. Select a Cell : Click on the cell where you want the result (monthly payment). Enter the PMT Function : Use the formula syntax: =PMT(rate, nper, pv, [fv], [type]) Input Arguments : rate : Interest rate per period (e.g., for a monthly rate, divide the annual rate by 12). nper : Total number of payment periods. pv : Present value (loan amount or investment). fv (optional) : Future value, usually 0 for loans. type (optional) : Payment timing: 0 (default): End of the period. 1: Beginning of the period. Press Enter : Excel will calculate and display the periodic payment. Example 1: Monthly Loan Payment Problem: You take a loan of $15,000 with an annual interest rate of 5%, to be repaid over 3 years (36 months). What is the monthly payment? Steps: Select a cell and enter: =PMT(5%/12, 3*12, -...