article

Showing posts with label web-development (PHP-MYSQL). Show all posts
Showing posts with label web-development (PHP-MYSQL). Show all posts

Tuesday, September 22, 2026

E-Commerce Home Furniture Using PHP MySQL PDO and MVC architecture

E-Commerce Home Furniture Using PHP MySQL PDO and MVC architecture - Complete Project

Source Code : https://github_____________________com/cai-ro-coders/-PH-Skip-navigation-Search-Create-Avatar-image-E-Commerce-Home-Furniture-Using-PHP-MySQL-PDO-and-MVC Core Features:
User & Account Management
Product recommendations
Shopping Cart
Checkout
Coupon and discount support
Python Django Stripe payment integration
Python Django PayPal payment integration
Real-time order tracking
Delivery address handling
Admin Panel
Customer Account
-Search filters
-Recommendations
-Mobile-friendly design
-Shopping Cart

Thursday, August 13, 2026

Human Resource Management System With Payroll, Attendance, Recruitment & Performance Using PHP MySQL PDO and MVC architecture - Complete Project

Human Resource Management System With Payroll, Attendance, Recruitment & Performance Using PHP MySQL PDO and MVC architecture - Complete Project

MVC folder structure:

project/
│
├── app/
│ ├── controllers/
│ ├── models/
│ ├── views/
│ └── helpers/

│ ├── config/
├── public/
├── assets/
│ ├── css/
│ ├── js/
│ ├── images/
│ └── uploads/
v │
├── database/
├── routes/
├── vendor/
└── index.php

Core Features:
Source Code : https://github________________com/cai-ro-coders/Human-Resource-Management-System-With-Payroll-Using-PHP-MySQL-PDO-and-MVC-architecture- Employee Management & HR Administration

Manage all employee information and HR activities from a centralized system.
Manage complete employee profiles and personal information
Maintain a centralized employee database (personal, company, bank, and documents)
Organize employees by department, designation, and role
Manage HR activities such as promotions, transfers, warnings, work trips, and terminations
Control HR settings, permissions, and workflows

Attendance, Leave & Holiday Management

Track working hours, manage leave policies, and handle company holidays efficiently.
Track daily employee attendance
Support customizable shifts and attendance policies
Allow attendance regularization requests
Create multiple leave types and leave policies
Employees can apply for leave online
Track leave balances and leave history
Create and manage company holiday lists

Payroll & Payslip Management

Automate salary calculation and manage payroll processes with accuracy.
Configure salary components such as allowances, commissions, overtime, and deductions
Support weekly, bi-weekly, and monthly payroll cycles
Generate and download employee payslips
Maintain payroll history

Recruitment & Applicant Tracking (ATS)

Handle the complete hiring process from job posting to employee selection.
Create and manage job openings
Track candidate applications
Move applicants through different hiring stages
Track candidate status from application to selection
Store candidate information in one place
Convert selected candidates into employees

Employee Onboarding

Manage employee entry and exit processes in a structured way.
Manage employee joining process
Assign departments, roles, and documents
Set up employee access and profile
Handle employee exit process
Manage resignation and exit records
Track asset return and final status

Performance Management

Measure, review, and improve employee performance using structured tools.
Define indicator categories and performance indicators
Set goal types with timelines
Employees can manage their own goals
Run review cycles and employee evaluations
Track employee performance ratings

Training & Learning Management (LMS)

Organize training programs and track employee skill development.
Create training types and training programs
Schedule and manage training sessions
Assign training to employees
Track training completion and progress

Employee Self-Service (ESS) Portal

Give employees direct access to their own HR information and actions.
Employees can view and manage their own profiles
Apply for leave and view attendance
Download payslips and documents
View assigned assets and contracts
Document, Asset & Contract Management

Store, organize, and manage company documents, assets, and contracts securely.
Upload and store HR and company documents
Organize files using document categories
Use predefined HR document templates
Track document acknowledgments
Assign company assets to employees
Track asset allocation, status, and depreciation
Store and manage employee contracts
Track contract validity and details
Meetings & Internal Management

Manage meetings and internal HR coordination in an organized way.
Create and manage meeting types and meeting rooms
Manage meeting attendees
Record meeting minutes and action items
Track meeting schedules and follow-ups

Wednesday, August 5, 2026

Employee Management System Using PHP MySQL PDO and MVC architecture - Complete Project

Employee Management System Using PHP MySQL PDO and MVC architecture - Complete Project

MVC folder structure:

project/
│
├── app/
│ ├── controllers/
│ ├── models/
│ ├── views/
│ └── helpers/

│ ├── config/
├── public/
├── assets/
│ ├── css/
│ ├── js/
│ ├── images/
│ └── uploads/
v │
├── database/
├── routes/
├── vendor/
└── index.php

Core Features:
- Employee Information Management
Store employee profiles
Personal and contact information
Employment details (position, department, salary, hire date)
Emergency contacts and documents
- User Authentication and Role Management
Secure login/logout
Role-based access (Admin, HR, Manager, Employee)
Password management
- Attendance Management
Time-in and time-out recording
Daily attendance tracking
Late, undertime, and overtime monitoring
Attendance reports
- Leave Management
Leave application and approval
Vacation, sick, maternity, and emergency leave tracking
Leave balance monitoring
Leave history
- Payroll Management
Salary computation
Overtime and deductions
Tax and benefits calculations
Payslip generation
- Department and Position Management
Create and manage departments
Assign employees to departments
Manage job positions and responsibilities
- Performance Evaluation
Employee performance reviews
Goal setting and tracking
Manager feedback
Performance reports
- Employee Scheduling
Work shift assignment
Schedule management
Holiday and rest day configuration
- Document Management
Upload and store employee documents
Contracts and certificates
Government IDs and compliance documents
- Notifications and Announcements
Company announcements
Leave approval notifications
Payroll reminders
Birthday and work anniversary alerts
- Employee Self-Service Portal
View personal information
Update contact details
Apply for leave
View attendance and payslips
Download company documents
- Audit Logs and Security
Track user activities
Record system changes
Data backup and recovery
Source Code : https://github__________com/cai-ro-coders/Employee-Management-System-Using-PHP-MySQL-PDO-and-MVC-architecture---Complete-Project

Saturday, August 1, 2026

CRM Customer Relationship Management system Using PHP MySQL PDO and MVC architecture - Complete Project

CRM Customer Relationship Management system Using PHP MySQL PDO and MVC architecture - Complete Project

MVC folder structure:

project/
│
├── app/
│ ├── controllers/
│ ├── models/
│ ├── views/
│ └── helpers/

│ ├── config/
├── public/
├── assets/
│ ├── css/
│ ├── js/
│ ├── images/
│ └── uploads/
v │
├── database/
├── routes/
├── vendor/
└── index.php

Core Features:
1. Contact Management
Store customer and prospect information
Manage names, emails, phone numbers, addresses, and social profiles
Keep a complete customer interaction history
2. Lead Management
Capture leads from websites, forms, and campaigns
Track lead status throughout the sales pipeline
Assign leads to sales representatives
Score and prioritize leads
3. Sales Pipeline Management
Visualize sales opportunities
Track deals from initial contact to closing
Monitor deal stages and probability of success
Forecast future sales revenue
4. Customer Communication
Email integration
SMS and messaging support
Call logging and call history
Meeting scheduling and reminders
5. Task and Activity Management
Create tasks and to-do lists
Schedule appointments
Set follow-up reminders
Track completed activities
6. Customer Support Management
Ticket creation and tracking
Complaint and issue management
Service request handling
Knowledge base integration
7. Marketing Automation
Email marketing campaigns
Customer segmentation
Campaign performance tracking
Automated follow-up workflows
8. Reporting and Analytics
Sales reports
Customer acquisition reports
Performance dashboards
KPI monitoring
Revenue analysis
9. Document Management
Store contracts, proposals, and invoices
Upload customer-related files
Version control
Secure document sharing
10. Workflow Automation
Automate repetitive tasks
Approval workflows
Automatic notifications
Trigger-based actions
11. User and Role Management
User authentication
Role-based access control
Permission management
Activity logs
12. Customer Interaction History
Record calls, emails, chats, and meetings
Timeline of customer interactions
Purchase history
Notes and comments
13. Calendar and Scheduling
Appointment management
Team calendars
Meeting invitations
Event reminders
14. Integration Capabilities
Email services (e.g., Outlook, Gmail)
ERP systems
Accounting software
E-commerce platforms
15. Mobile Access
Mobile-friendly interface
Android and iOS support
Offline access
Push notifications
16. Customer Portal (Optional)
Customers can view tickets
Track orders
Update personal information
Download invoices and documents
17. Security Features
Data encryption
Backup and recovery
Multi-factor authentication (MFA)
Audit logs
Privacy and compliance controls
18. Dashboard
Personalized dashboard
Sales overview
Recent activities
Upcoming tasks
Key business metrics
give me a prompt
Source Code : https://github_______com/cai-ro-coders/CRM-Customer-Relationship-Management-system-Using-PHP-MySQL-PDO-and-MVC-architecture

Thursday, July 23, 2026

Inventory Management System Using PHP MySQL PDO and MVC architecture - Complete Project

Inventory Management System Using PHP MySQL PDO and MVC architecture - Complete Project

Inventory Management System Using PHP MySQL PDO and MVC architecture - Complete Project Complete Project Inventory Management System Using PHP MySQL PDO and MVC architecture - Complete Project
MVC Architecture PHP, MySQL, Bootstrap 5, HTML5, CSS3, JavaScript, jQuery, AJAX, PDO for database operations and MVC architecture

MVC folder structure:

project/
│
├── app/
│ ├── controllers/
│ ├── models/
│ ├── views/
│ └── helpers/

│ ├── config/
├── public/
├── assets/
│ ├── css/
│ ├── js/
│ ├── images/
│ └── uploads/
v │
├── database/
├── routes/
├── vendor/
└── index.php

Core Features:
1. Product Management
Add, edit, and delete products
Store product details (name, SKU, barcode, category, price, supplier)
Organize products into categories
2. Stock Management
Track stock quantities in real time
Record stock-in and stock-out transactions
Monitor stock levels across locations (if applicable)
3. Inventory Monitoring
View current inventory status
Set minimum and maximum stock levels
Receive low-stock and out-of-stock alerts
4. Purchase Management
Create and manage purchase orders
Record supplier deliveries
Update inventory automatically after receiving items
5. Sales Management
Record sales transactions
Automatically deduct sold items from inventory
Generate sales receipts or invoices
6. Supplier Management
Maintain supplier information
Track supplier performance and purchase history
Manage supplier contacts
7. Customer Management (Optional)
Store customer information
Track customer purchase history
Support customer-specific pricing or discounts
8. Barcode/QR Code Support
Generate product barcodes or QR codes
Scan items for faster stock updates and sales processing
9. Reporting and Analytics
Inventory valuation reports
Stock movement reports
Sales and purchase reports
Best-selling and slow-moving products
Profit and loss summaries
10. User and Role Management
Secure user login
Role-based access (e.g., Admin, Manager, Staff)
Activity logs and audit trails
11. Notifications and Alerts
Low-stock alerts
Expiring product notifications (for perishable goods)
Reorder reminders
12. Search and Filtering
Search products by name, SKU, or barcode
Filter by category, supplier, stock status, or date
13. Data Backup and Security
Regular database backups
Secure authentication
Data encryption and recovery options
14. Dashboard
Overview of total products, stock value, low-stock items, and recent transactions
Visual charts for inventory and sales trends
Source Code : https://github__________com/cai-ro-coders/Inventory-Management-System-Using-PHP-MySQL-PDO-and-MVC-architecture---Complete-Project

Wednesday, July 15, 2026

E Commerce Industrial Tool Shop Using PHP MySQL PDO and MVC architecture - Complete Project

E Commerce Industrial Tool Shop Using PHP MySQL PDO and MVC architecture - Complete Project

Complete Project Ecommerce
MVC Architecture PHP, MySQL, Bootstrap 5, HTML5, CSS3, JavaScript, jQuery, AJAX, PDO for database operations and MVC architecture


Core Features:
Product recommendations
Cart management
Coupon and discount support
Stripe payment integration (credit/debit cards)
PayPal payment integration
Real-time order tracking
Delivery address handling
Admin Panel
Customer Account
-Search filters
-Recommendations
-Mobile-friendly design
-Shopping Cart

MVC folder structure:

project/
│
├── app/
│ ├── controllers/
│ ├── models/
│ ├── views/
│ └── helpers/

│ ├── config/
├── public/
├── assets/
│ ├── css/
│ ├── js/
│ ├── images/
│ └── uploads/
v │
├── database/
├── routes/
├── vendor/
└── index.php

Source Code : https://github__________com/cai-ro-coders/E-Commerce-Industrial-Tool-Shop-Using-PHP-MySQL-PDO-and-MVC-architecture---Complete-Project-

Friday, July 19, 2024

Next.js 14 CRUD (Create Read Update and Delete) with PHP MySQL

Next.js 14 CRUD (Create Read Update and Delete) with PHP MySQL

Install nextjs
https://nextjs.org/
npx create-next-app@latest

install axios
npm install axios
https://www.npmjs.com/package/axios
app\page.js
//app\page.js
import ListUser from '@/components/ListUser'
import { Suspense } from "react";
import Link from "next/link";

export default function Home() {
  return (
    <div className="w-screen py-20 flex justify-center flex-col items-center">
      <div className="flex items-center justify-between gap-1 mb-5">
        <h1 className="text-4xl font-bold">Next.js 14 CRUD (Create Read Update and Delete) with PHP MySQL</h1>
      </div>    
      <div className="overflow-x-auto">
          <div className="mb-2 w-full text-right">
            <Link
              href="/users/create"
              className="btn btn-primary">
              Add New User
            </Link>
          </div>
        <Suspense fallback="Loading...">
            <ListUser/>
          </Suspense>
      </div>  
    </div>
  );
}
components\ListUser.jsx
//components\ListUser.jsx
"use client";

import axios from 'axios';
import { useEffect, useState } from "react";
import Link from "next/link";

export default function ListUser() {

    const [users, setUsers] = useState([]);

    useEffect(() => {
        getUsers();
    }, []);
 
    function getUsers() { 
        axios.get('http://localhost:8888/devproject/nexjsphpmysl/api/').then(function(response) {
            console.log(response.data);
            setUsers(response.data);
        });
    }

    const deleteUser = (id) => {
        axios.delete(`http://localhost:8888/devproject/nexjsphpmysl/api/${id}/delete`).then(function(response){
            console.log(response.data);
            getUsers();
        });
    }
    
    return (
        <table className="table table-zebra">
            <thead className="text-sm text-gray-700 uppercase bg-gray-50">
                <tr>
                    <th className="py-3 px-6">#</th>
                    <th className="py-3 px-6">Name</th>
                    <th className="py-3 px-6">Email</th>
                    <th className="py-3 px-6">Mobile</th>
                    <th className="py-3 px-6 text-center">Actions</th>
                </tr>
            </thead>
            <tbody>
                {users.map((user, key) =>
                    <tr key={key} className="bg-white border-b">
                        <td className="py-3 px-6">{user.id}</td>
                        <td className="py-3 px-6">{user.name}</td>
                        <td className="py-3 px-6">{user.email}</td>
                        <td className="py-3 px-6">{user.mobile}</td>
                        <td className="flex justify-center gap-1 py-3">
                            <Link
                                href={`/users/view/${user.id}`} 
                                className="btn btn-success">
                                View
                            </Link>
                            <Link className="btn btn-info" href={`users/edit/${user.id}/`}>
                                Edit
                            </Link>
                            <button onClick={() => deleteUser(user.id)} className="btn btn-error">Delete</button>
                        </td>
                    </tr>
                )}
            </tbody>
        </table>
    )
}
app\users\create\page.jsx
//app\users\create\page.jsx
"use client";

import React, { useState } from "react";
import axios from 'axios' //npm install axios https://www.npmjs.com/package/axios

const Addnewuser = () => {
    const [inputs, setInputs] = useState([]);
 
    const handleChange = (event) => {
        const name = event.target.name;
        const value = event.target.value;
        setInputs(values => ({...values, [name]: value}));
    }

    const handleSubmit = (event) => {
        event.preventDefault();

        axios.post('http://localhost:8888/devproject/nexjsphpmysl/api/save', inputs).then(function(response){
            console.log(response.data);
            window.location.href = '/';
        });
    }

    return (
    <div className="max-w-md mx-auto mt-5">
        <h1 className="text-2xl text-center mb-2">Add New User</h1>
        <div>
        <form onSubmit={handleSubmit}>
        <div className="mb-5">
          <label htmlFor="name" className="block text-sm font-medium text-gray-900">
            Name
          </label>
          <input
            type="text"
            name="name"
            id="name"
            className="input input-bordered input-primary w-full max-w-xs"
            placeholder="Name..."
            onChange={handleChange}
          />
        </div>
        <div className="mb-5">
          <label htmlFor="email" className="block text-sm font-medium text-gray-900">
            Email
          </label>
          <input
            type="email"
            name="email"
            id="email"
            className="input input-bordered input-primary w-full max-w-xs"
            placeholder="email..."
            onChange={handleChange}
          />
        </div>
        <div className="mb-5">
          <label htmlFor="mobile" className="block text-sm font-medium text-gray-900">
            Mobile
          </label>
          <input
            type="text"
            name="mobile"
            id="mobile"
            className="input input-bordered input-primary w-full max-w-xs"
            placeholder="mobile..."
            onChange={handleChange}
          />
        </div>
        <button type="submit" className="btn btn-primary">Add New User</button> 
      </form>
    </div>
    </div>
  );
};
   
export default Addnewuser;
app\users\edit\[id]\page.jsx
//app\users\edit\[id]\page.jsx
"use client";
  
import React, { useState, useEffect } from 'react';
import axios from 'axios' //npm install axios https://www.npmjs.com/package/axios
import { useParams } from 'next/navigation'
 
export default function Edituser() {
    const [inputs, setInputs] = useState([]);
    const {id}=useParams();
    console.log(id);
 
    useEffect(() => {
        getUser();
    }, []);
 
    function getUser() {
        axios.get(`http://localhost:8888/devproject/nexjsphpmysl/api/${id}`).then(function(response) {
            console.log(response.data);
            setInputs(response.data);
        });
    }

    const handleChange = (event) => {
        const name = event.target.name;
        const value = event.target.value;
        setInputs(values => ({...values, [name]: value}));
    }

    const handleSubmit = (event) => {
        event.preventDefault();
 
        axios.put(`http://localhost:8888/devproject/nexjsphpmysl/api/${id}/edit`, inputs).then(function(response){
            console.log(response.data);
            window.location.href = '/';
        });
         
    }
    return (
    <div className="max-w-md mx-auto mt-5">
      <h1 className="text-2xl text-center mb-2">Edit Form</h1>
            <form onSubmit={handleSubmit}> 
                <div className="mb-3 mt-3">
                    <label className="block text-sm font-medium text-gray-900"> ID:</label>
                    <input type="text" id="id" name="id" value={id} disabled />
                </div>
                <div className="mb-3 mt-3">
                    <label className="block text-sm font-medium text-gray-900"> Full Name:</label>
                    <input type="text" className="input input-bordered input-primary w-full max-w-xs" placeholder="Enter Your Full Name" name="name"
                    value={inputs.name || ''} 
                    onChange={handleChange}/>
                </div>
                <div className="mb-3 mt-3">
                    <label className="block text-sm font-medium text-gray-900">Email:</label>
                    <input type="text" className="input input-bordered input-primary w-full max-w-xs" id="email" placeholder="Enter email" name="email"
                    value={inputs.email || ''} 
                    onChange={ handleChange}/>
                </div>
                <div className="mb-3 mt-3">
                    <label className="block text-sm font-medium text-gray-900">Mobile:</label>
                    <input type="text" className="input input-bordered input-primary w-full max-w-xs" id="mobile" placeholder="Enter mobile" name="mobile"
                    value={inputs.mobile || ''} 
                    onChange={ handleChange}/>
                </div>
                <button type="submit" name="update"  className="btn btn-primary">Update</button>
            </form>
    </div>
  );
}
app\users\view\[id]\page.jsx
//app\users\view\[id]\page.jsx
"use client";
  
import React, { useState, useEffect } from 'react';
import axios from 'axios' //npm install axios https://www.npmjs.com/package/axios
import { useParams } from 'next/navigation'
 
export default function ViewUser() {
    const {id}=useParams();
  
    console.log(id);
  
    const[user,setUser]=useState([]);
   
    useEffect(()=>{
        fetchUser();
    },[id]);
   
    const fetchUser=async()=>{
        try{
        const result=await axios.get("http://localhost:8888/devproject/nexjsphpmysl/api/"+id);
          console.log(result.data);
          setUser(result.data)
   
        }catch(err){
            console.log("Something Wrong");
        }
    }
  
    return (
    <div className="max-w-2xl mx-auto mt-5">
      <h1 className="text-2xl text-center mb-2">View User</h1>
      <table className="table table-zebra">
          <thead className="text-sm text-gray-700 uppercase bg-gray-50">
            <tr>
              <th>S No.</th>
              <th>Name</th>
              <th>Email</th>         
              <th>Mobile</th>      
            </tr>
          </thead>
          <tbody>
            <tr>
                <td>{user.id}</td>
                <td>{user.name}</td>
                <td>{user.email}</td>
                <td>{user.mobile}</td>
            </tr>
          </tbody>
      </table>
    </div>
  );
}
devproject/nexjsphpmysl/api/index.php
//devproject/nexjsphpmysl/api/index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");

include 'DbConnect.php';
$objDb = new DbConnect;
$conn = $objDb->connect();

$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
    case "GET":
        $sql = "SELECT * FROM users";
        $path = explode('/', $_SERVER['REQUEST_URI']);
        if (isset($path[4]) && is_numeric($path[4])) {
            $sql .= " WHERE id = :id";
            $stmt = $conn->prepare($sql);
            $stmt->bindParam(':id', $path[4]);
            $stmt->execute();
            $users = $stmt->fetch(PDO::FETCH_ASSOC);
        } else {
            $stmt = $conn->prepare($sql);
            $stmt->execute();
            $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }

        echo json_encode($users);
        break;

    case "POST":
        $user = json_decode(file_get_contents('php://input'));
        $sql = "INSERT INTO users(id, name, email, mobile, created_at) VALUES(null, :name, :email, :mobile, :created_at)";
        $stmt = $conn->prepare($sql);
        $created_at = date('Y-m-d');
        $stmt->bindParam(':name', $user->name);
        $stmt->bindParam(':email', $user->email);
        $stmt->bindParam(':mobile', $user->mobile);
        $stmt->bindParam(':created_at', $created_at);

        if ($stmt->execute()) {
            $response = ['status' => 1, 'message' => 'Record created successfully.'];
        } else {
            $response = ['status' => 0, 'message' => 'Failed to create record.'];
        }
        echo json_encode($response);
        break;

    case "PUT":
        $user = json_decode(file_get_contents('php://input'));
        $sql = "UPDATE users SET name= :name, email =:email, mobile =:mobile, updated_at =:updated_at WHERE id = :id";
        $stmt = $conn->prepare($sql);
        $updated_at = date('Y-m-d');
        $stmt->bindParam(':id', $user->id);
        $stmt->bindParam(':name', $user->name);
        $stmt->bindParam(':email', $user->email);
        $stmt->bindParam(':mobile', $user->mobile);
        $stmt->bindParam(':updated_at', $updated_at);

        if ($stmt->execute()) {
            $response = ['status' => 1, 'message' => 'Record updated successfully.'];
        } else {
            $response = ['status' => 0, 'message' => 'Failed to update record.'];
        }
        echo json_encode($response);
        break;

    case "DELETE":
        $sql = "DELETE FROM users WHERE id = :id";
        $path = explode('/', $_SERVER['REQUEST_URI']);

        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':id', $path[4]);

        if ($stmt->execute()) {
            $response = ['status' => 1, 'message' => 'Record deleted successfully. ' . $path[4] . ' '];
        } else {
            $response = ['status' => 0, 'message' => 'Failed to delete record.'];
        }
        echo json_encode($response);
        break;
}
devproject/nexjsphpmysl/api/DbConnect.php
//devproject/nexjsphpmysl/api/DbConnect.php
<?php
class DbConnect
{
    private $server = 'localhost';
    private $dbname = 'nextjsdb';
    private $user = 'root';
    private $pass = 'root';

    public function connect()
    {
        try {
            $conn = new PDO('mysql:host=' . $this->server . ';dbname=' . $this->dbname, $this->user, $this->pass);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;
        } catch (\Exception $e) {
            echo "Database Error: " . $e->getMessage();
        }
    }
}

devproject/nexjsphpmysl/api/.htaccess
RewriteEngine On
 
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Run C:\myapp-js>npm start

Check API Results in Postman
https://www.postman.com/downloads/
POST method : http://localhost/devproject/nexjsphpmysl/api/save
Get method : http://localhost/devproject/nexjsphpmysl/api/
PUT method : http://localhost/devproject/nexjsphpmysl/api/1
DELTE method : http://localhost/devproject/nexjsphpmysl/api/1

Wednesday, July 17, 2024

Next.js 14 Fetch data from the database using PHP API Mysql

Next.js 14 Fetch data from the database using PHP API Mysql

Install nextjs npx create-next-app@latest https://nextjs.org/docs/getting-started/installation
app\page.js
//app\page.js 
import UserDataComponent from '@/components/UserDataComponent'
import { Suspense } from "react";

export default async function Home() {
  return (
    <div className="w-screen py-20 flex justify-center flex-col items-center">
      <div className="flex items-center justify-between gap-1 mb-5">
        <h1 className="text-4xl font-bold">Next.js 14 Fetch data from the database using PHP API Mysql</h1>
      </div>    
      <div className="overflow-x-auto">
        <Suspense fallback="Loading...">
            <UserDataComponent/>
          </Suspense>
      </div>  
    </div>
  );
}
components\UserDataComponent.js
//components\UserDataComponent.js
"use client";

import Axios from 'axios';
import React, { useEffect, useState } from "react";

const UserDataComponent = () => {

    const [userData,setUserData]= useState([]);

    useEffect(() => {
        const fetchUsers = async () => {
            Axios.get('http://localhost:8888/devproject/getUserData.php')
            .then(function (data) {
                //handle success
                console.log('userData',data)
                setUserData(data.data)
            })
            .catch(function (error) {
                //handle error
                console.log(error)
            });
        }
        fetchUsers()
    }, [])
    

    return (
        <div>
        <h1>User  List</h1>
        <table className="table table-zebra">
        <thead className="text-sm text-gray-700 uppercase bg-gray-50">
            <tr>
            <th className="py-3 px-6">#</th>
            <th className="py-3 px-6">Name</th>
            <th className="py-3 px-6">Email</th>
            <th className="py-3 px-6">Password</th>
            </tr>
        </thead>
        <tbody>
            {userData.map((rs, index) => (
            <tr key={rs.id} className="bg-white border-b">
                <td className="py-3 px-6">{rs.id}</td>
                <td className="py-3 px-6">{rs.name}</td>
                <td className="py-3 px-6">{rs.email}</td>
                <td className="py-3 px-6">{rs.password}</td>
            </tr>
            ))}
        </tbody>
        </table>
        </div>
    )
}

export default UserDataComponent
run C:\nextjs>npm run dev

dbcon.php
//dbcon.php
<?php
//$mysqli = new mysqli("hostName", "dbUserId", "dbPassword", "dbName");
$mysqli = new mysqli("localhost", "root", "root", "devproject");
?>
getUserData.php
//getUserData.php
<?php
 //getUserData.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

//Database Connection
include 'dbcon.php';
$value=array();
$Sql_Query ="SELECT * from users";
$result = $mysqli->query($Sql_Query);
if (@$result->num_rows >0) {
    while($row[] = $result->fetch_assoc()) {
        $item = $row;
        $json = json_encode($item,JSON_PRETTY_PRINT);
    }
    echo @$json;
} else {
    echo json_encode($value,JSON_PRETTY_PRINT);;
}

$mysqli->close();
?>

Tuesday, April 2, 2024

PHP and MySQL Upload Image

PHP and MySQL Upload Image

Bootstrap 5 https://getbootstrap.com/docs/5.1/getting-started/download/
index.php
//index.php
<!DOCTYPE html>
<html lang="en">

<head>
    <title>PHP and MySQL Upload Image</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
    <style>
        .image-preview {
            background-image: url('avatar.png');
            width: 14%;
            height: 100px;
            background-size: cover;
            background-position: center;
            border-radius: 10px;
        }

        .photo {
            width: 50px;
            height: 50px;
            border-radius: 50%;
        }
    </style>
</head>

<body>
    <?php
    include "dbcon.php";
    $sql = "select * from users order by name";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->get_result();
    include "upload.php";
    ?>
    <div class="container">
        <h1 class="mb-5">PHP and MySQL Upload Image</h1>
        <div class="table-responsive">
            <h2>List of users</h2>
            <a class="btn btn-primary" href="#" data-bs-toggle="modal" data-bs-target="#modalAddnew">Add New</a>

            <table class="mt-5 table table-bordered table-striped">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Name</th>
                        <th scope="col">Photo</th>
                        <th scope="col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($result->num_rows > 0) {
                        $counter = 0;
                        foreach ($result as $row) {
                            $counter++;
                    ?>
                            <tr class="">
                                <td scope="row"><?= $counter ?></td>
                                <td><?= $row['name'] ?></td>
                                <td><img class="photo" src="uploads/<?= $row['photo'] ?>"></td>
                                <td>
                                    <a href="index.php?id=<?= $row['id'] ?>" onclick="return confirm('Are you sure you want to delete the user?')">
                                        <button type="button" class="btn btn-danger" title="delete the user">
                                            Delete
                                        </button>
                                    </a>
                                </td>
                            </tr>
                        <?php }
                    } else { ?>
                        <tr>
                            <td>No users to display</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="modalAddnew" tabindex="-1" role="dialog" aria-labelledby="modalTitleId" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitleId">
                        Add New
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="" method="post" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label for="name" class="form-label">Name</label>
                            <input type="text" class="form-control" name="name" id="name" aria-describedby="helpId" placeholder="Enter a Name" />
                            <div class="text-danger"><?= $name_err ?></div>
                        </div>
                        <div class="mb-3">
                            <label for="photo" class="form-label">Select A Photo</label>
                            <input type="file" class="form-control" name="photo" id="photo" placeholder="" aria-describedby="fileHelpId" onchange="previewImg(this)" />
                            <div id="fileHelpId" class="form-text">Allowed file types: jpg, jpeg, png</div>
                            <div class="text-danger"><?= $photo_err ?></div>
                        </div>
                        <div class="mb-5 image-preview"></div>
                        <button type="submit" name="submit" class="btn btn-primary">
                            Submit
                        </button>
                    </form>
                    <div class="text-danger"><?= $err_msg ?></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        Close
                    </button>
                </div>
            </div>
        </div>
    </div>
    <script>
        function previewImg(input) {
            if (input.files && input.files[0] != "") {
                var reader = new FileReader();
                reader.onload = function(e) {
                    $(".image-preview").css('background-image', 'url(' + e.target.result + ')');
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>

</html>
dbcon.php
//dbcon.php
<?php

$server = "localhost";
$uid = "root";
$pwd = "root";
$dbname = "devproject";
$conn = new mysqli($server, $uid, $pwd, $dbname);

if ($conn->connect_error)
    die("database connection error " . $conn->connect_error);
upload.php
//  upload.php
<?php
$error = false;
$name_err = $photo_err = $err_msg = "";
$valid_ext = array('jpg', 'jpeg', 'png');

$target_dir = "uploads/";
$photo = "";

if (isset($_REQUEST['id']) && $_REQUEST['id'] != "") {
    // delete image
    $id = $_REQUEST['id'];

    $sql = "select photo from users where id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows == 1) {
        $row = $result->fetch_assoc();
        $photo = $row['photo'];
    }

    if (file_exists($target_dir . $photo))
        unlink($target_dir . $photo);

    $sql = "delete from users where id=?";
    $stmt->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    header("location:index.php");
}

if(isset($_POST['submit'])){
    $name = $_POST['name'];

    if ($name ==""){
        $name_err = "Please enter the name";
        $error = true;
    }

    if($_FILES['photo']['name'] ==""){
        $photo_err = "Please select a photo";
        $error = true;
    }

    if (!$error){
        $image_name = $_FILES['photo']['name'];
        $image_tmp = $_FILES['photo']['tmp_name'];
        $image_size = $_FILES['photo']['size'];

        // check for extension

        $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
        if (in_array($ext, $valid_ext)) {
            // valid extension
            if (exif_imagetype($image_tmp) == IMAGETYPE_JPEG || exif_imagetype($image_tmp) == IMAGETYPE_PNG) {
                // valid image
                if ($image_size > 4000000) {
                    // exceeds 4M
                    $err_msg = "image size exceeds 4M";
                } else {
                    // upload
                    $new_image = time() . "-" . basename($image_name);

                    try {
                        move_uploaded_file($image_tmp, $target_dir . $new_image);

                        // insert
                        try {
                            $sql = "insert into users (name, photo) values (?, ?)";
                            $stmt = $conn->prepare($sql);
                            $stmt->bind_param("ss", $name, $new_image);
                            $stmt->execute();
                            header("location:index.php");
                        } catch (Exception $e) {
                            $err_msg = $e->getMessage();
                        }
                    } catch (Exception $e) {
                        $err_msg = $e->getMessage();
                    }
                }
            } else {
                $err_msg = "Not a valid image file";
            }
        } else {
            $err_msg = "Not a valid extension";
        }
    }

}
Github - PHP and MySQL Upload Image

Thursday, September 7, 2023

PHP Mysql Comment Jquery Ajax

PHP Mysql Comment Jquery Ajax

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js

Database Table 
CREATE TABLE `msg` (
  `id` int(11) NOT NULL,
  `name` text NOT NULL,
  `msg` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<link rel="stylesheet" href="style.css">
    <title>PHP Mysql Comment Jquery Ajax</title>
</head>
<body>
<div class="container mt-5">
    <div class="d-flex justify-content-center row">
        <div class="col-md-8">
            <div class="d-flex flex-column comment-section">
                <div class="bg-white p-2">
                    <div class="d-flex flex-row user-info"><img class="rounded-circle" src="https://i.imgur.com/RpzrMR2.jpg" width="40">
                        <div class="d-flex flex-column justify-content-start ml-2"><span class="d-block font-weight-bold name">Marry Andrews</span><span class="date text-black-50">Shared publicly - Jan 2020</span></div>
                    </div>
                    <div class="mt-2">
                        <p class="comment-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
                    </div>
                </div>
                <div class="bg-white">
                    <div class="d-flex flex-row fs-12">
                        <div class="like p-2 cursor"><i class="fa fa-thumbs-o-up"></i><span class="ml-1">Like</span></div>
                        <div class="like p-2 cursor"><i class="fa fa-commenting-o"></i><span class="ml-1">Comment</span></div>
                        <div class="like p-2 cursor"><i class="fa fa-share"></i><span class="ml-1">Share</span></div>
                    </div>
                </div>
				<form id="form">
                <div class="bg-light p-2">
                    <div class="d-flex flex-row align-items-start"><img class="rounded-circle" src="https://i.imgur.com/RpzrMR2.jpg" width="40">
					<input type="hidden" id="name" placeholder="Enter your name" value="Cairocoders Ednalan" required>
					<textarea class="form-control ml-1 shadow-none textarea" id="msg"></textarea>
					</div>
                    <div class="mt-2 text-right">
					<button class="btn btn-primary btn-sm shadow-none" type="button" id="btn">Post comment</button>
					<button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button>
					</div>
                </div>
				</form>
				<hr>
				<div class="content" id="content"></div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script>
<script>
$(document).ready(function(){
    function loadData(){
        $.ajax({
            url: 'select-data.php',
            type: 'POST',
            success: function(data){
                $("#content").html(data);
            }
        });
    }

    loadData();

    $("#btn").on("click", function(e){
        e.preventDefault();
        var name = $("#name").val();
        var msg = $("#msg").val();

		$.ajax({
			url: 'insert-data.php',
            type: 'POST',
            data: {name: name, msg: msg},
            success: function(data){
                if (data == 1) {
                    loadData();
                    alert('Comment Submitted Successfully.');
                    $("#form").trigger("reset");
                }else {
                    alert("Comment Can't Submit.");
                }
            }
        });
    });
});
</script>
</body>
</html>
config.php
//config.php
<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "devdb";

    $conn = mysqli_connect($servername, $username, $password, $database);

    if (!$conn) {
        echo "Connection Failed.";
    }
?>
insert-data.php
//insert-data.php
<?php
    include 'config.php';

    $name = $_POST['name'];
    $msg = $_POST['msg'];
    
    $sql = "INSERT INTO msg (name, msg) VALUES ('$name', '$msg')";
    $result = mysqli_query($conn, $sql);

    if ($result) {
        echo 1;
    }else {
        echo 0;
    }
?>
select-data.php
//select-data.php
<?php
    include 'config.php';

    $sql = "SELECT * FROM msg ORDER BY id DESC";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="card mb-4">
    <div class="card-body">
		<p><?php echo $row['msg']; ?></p>
        <div class="d-flex justify-content-between">
            <div class="d-flex flex-row align-items-center">
                <img src="https://i.imgur.com/RpzrMR2.jpg" alt="avatar" width="25" height="25" />
                <p class="small mb-0 ms-2"><?php echo $row['name']; ?></p>
            </div>
        </div>
    </div>
</div>
<?php } } ?>
style.css
//style.css
body{background: #eee}
.date{font-size: 12px}
.comment-text{font-size: 14px}
.fs-12{font-size: 14px}
.shadow-none{box-shadow: none}
.name{color: #007bff}
.cursor:hover{color: blue}
.cursor{cursor: pointer}
.textarea{resize: none}

Wednesday, August 30, 2023

PHP Mysql Jquery Ajax Pagination

PHP Mysql Jquery Ajax Pagination

Create Database And Table
CREATE TABLE `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;

https://gist.github.com/adhipg/1600028#file-countries-sql

Create a Database Connection File db.php

//db.php
<?php
    $servername='localhost';
    $username='root';
    $password='';
    $dbname = "devdb";
    $conn=mysqli_connect($servername,$username,$password,"$dbname");
      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
        }
?>
Download simple-bootstrap-paginator Plugin https://github.com/jorgefernando1/simple-bootstrap-paginator

Create List File ajax-pagination.php
//ajax-pagination.php
<!DOCTYPE html>
<html>
<head>
    <title>PHP Mysql Jquery Ajax Pagination</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script>
    <script src="simple-bootstrap-paginator.js"></script>
</head>
<body>
<div class="container">   
    <?php
        include_once("db.php");
        $perPage = 5;
        $sqlQuery = "SELECT * FROM country";
        $result = mysqli_query($conn, $sqlQuery);
        $totalRecords = mysqli_num_rows($result);
        $totalPages = ceil($totalRecords/$perPage);
    ?>
	<h2 class='w-100 d-flex justify-content-center p-3'>PHP Mysql Jquery Ajax Pagination</h2>
    <div class="row">
        <table class="table table-hover table-bordered">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody id="content">     
            </tbody>
        </table>   
        <div id="pagination"></div>    
        <input type="hidden" id="totalPages" value="<?php echo $totalPages; ?>">    
    </div>    
</div>
<script>
    $(document).ready(function(){
    var totalPage = parseInt($('#totalPages').val());   
    var pag = $('#pagination').simplePaginator({
        totalPages: totalPage,
        maxButtonsVisible: 5,
        currentPage: 1,
        nextLabel: 'Next',
        prevLabel: 'Prev',
        firstLabel: 'First',
        lastLabel: 'Last',
        clickCurrentPage: true,
        pageChange: function(page) {         
            $("#content").html('<tr><td colspan="6"><strong>loading...</strong></td></tr>');
            $.ajax({
                url:"get_data.php",
                method:"POST",
                dataType: "json",       
                data:{page: page},
                success:function(responseData){
					console.log(responseData);
                    $('#content').html(responseData.html);
                }
            });
        }
    });
});
</script>
</body>
</html>
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js

Create Get Data PHP File get_data.php
// get_data.php
<?php
include_once("db.php");
$perPage = 10;
if (isset($_POST["page"])) { 
    $page  = $_POST["page"]; 
} else { 
    $page=1; 
};  
$startFrom = ($page-1) * $perPage;  
$sqlQuery = "SELECT * FROM country ORDER BY id ASC LIMIT $startFrom, $perPage";  
$result = mysqli_query($conn, $sqlQuery); 
$paginationHtml = '';
while ($row = mysqli_fetch_assoc($result)) {  
    $paginationHtml.='<tr>';  
    $paginationHtml.='<td>'.$row["id"].'</td>';
    $paginationHtml.='<td>'.$row["country"].'</td>';
    $paginationHtml.='</tr>';  
} 
$jsonData = array(
    "html"  => $paginationHtml,  
);
echo json_encode($jsonData); 
?>

Wednesday, June 21, 2023

React JS Registration with PHP Mysql

React JS Registration with PHP Mysql

React JS
https://create-react-app.dev/

Create Project
C:\react-js>npx create-react-app my-app

Run
C:\react-js\my-app> npm start

C:\react-js\my-app\src\App.js

//C:\react-js\my-app\src\App.js
import React from "react";
import Registration from "./components/Registration";
import './App.css';

function App() {
  return (
    <>
      <Registration />
    </>
  );
}

export default App
C:\react-js\my-app\src\components\Registration.js
//C:\react-js\my-app\src\components\Registration.js
import React, { useState, useEffect } from "react";

function Registration(){
    const [user, setUser] = useState("");
    const [email, setEmail] = useState("");
    const [pass1, setPass1] = useState("");
    const [pass2, setPass2] = useState("");
    const [error, setError] = useState("");
    const [msg, setMsg] = useState("");

    useEffect(() => {
        setTimeout(function(){
            setMsg("");
        }, 15000);
    }, [msg]);

    const handleInputChange = (e, type) => {
        switch(type){
            case "user":
                setError("");
                setUser(e.target.value);
                if(e.target.value === ""){
                    setError("Username has left blank!");
                }
                break;
            case "email":
                setError("");
                setEmail(e.target.value);
                if(e.target.value === ""){
                    setError("Email has left blank!");
                }
                break;
            case "pass1":
                setError("");
                setPass1(e.target.value);
                if(e.target.value === ""){
                    setError("Password has left blank!");
                }
                break;
            case "pass2":
                setError("");
                setPass2(e.target.value);
                if(e.target.value === ""){
                    setError("Confirm password has left blank!");
                }
                else if(e.target.value !== pass1){
                    setError("Confirm password does not match!")
                }
                break;
            default:
        }
    }

    function handleSubmit(){
        if(user !== "" && email !== "" && pass1 !== "" && pass2 !== ""){
            var url = "http://localhost/devtest/reactjs/registration.php";
            var headers = {
                "Accept": "application/json",
                "Content-Type": "application/json"
            };
            var Data = {
                user: user,
                email: email,
                pass: pass2
            }
            fetch(url, {
                method: "POST",
                headers: headers,
                body: JSON.stringify(Data)
            }).then((response) => response.json())
            .then((response) => {
                setMsg(response[0].result);
            }).catch((err) =>{
                setError(err);
                console.log(err);
            });
            setUser("");
            setEmail("");
            setPass1("");
            setPass2("");
        }
        else{
            setError("All fields are required!");
        }
    }

    function checkUser(){
        var url = "http://localhost/devtest/reactjs/checkuser.php";
        var headers = {
            "Accept": "application/json",
            "Content-Type": "application/json"
        };
        var Data = {
            user: user
        }
        fetch(url, {
            method: "POST",
            headers: headers,
            body: JSON.stringify(Data)
        }).then((response) => response.json())
        .then((response) => {
            setError(response[0].result);
        }).catch((err) =>{
            setError(err);
            console.log(err);
        });
    }

    function checkEmail(){
        var url = "http://localhost/devtest/reactjs/checkemail.php";
        var headers = {
            "Accept": "application/json",
            "Content-Type": "application/json"
        };
        var Data = {
            email: email
        }
        fetch(url, {
            method: "POST",
            headers: headers,
            body: JSON.stringify(Data)
        }).then((response) => response.json())
        .then((response) => {
            setError(response[0].result);
        }).catch((err) =>{
            setError(err);
            console.log(err);
        });
    }

    function checkPassword(){
        if(pass1.length < 8){
            setError("Password is less than 8 characters!")
        }
    }

    return(
        <>
        <section className="vh-100 bg-image" style={{backgroundImage: 'url("https://images.unsplash.com/photo-1495195129352-aeb325a55b65")'}}>
          <div className="mask d-flex align-items-center h-100 gradient-custom-3">
            <div className="container h-100">
              <div className="row d-flex justify-content-center align-items-center h-100">
                <div className="col-12 col-md-9 col-lg-7 col-xl-6">
                  <div className="card" style={{borderRadius: 15}}>
                    <div className="card-body p-5">
                      <h2 className="text-uppercase text-center mb-5">Create an account</h2>
                      <p>
                          {
                              msg !== "" ?
                              <span className="success">{msg}</span> :
                              <span className="error">{error}</span>
                          }
                      </p>
                        <div className="form-outline mb-4">
                          <input 
                              type="text" 
                              name="user"
                              className="form-control form-control-lg"
                              value={user}
                              onChange={(e) => handleInputChange(e, "user")}
                              onBlur={checkUser}
                          />
                          <label className="form-label">Your User Name</label>
                        </div>
                        <div className="form-outline mb-4">
                          <input 
                                type="email" 
                                name="email"
                                className="form-control form-control-lg"
                                value={email}
                                onChange={(e) => handleInputChange(e, "email")}
                                onBlur={checkEmail}
                            />
                          <label className="form-label">Your Email</label>
                        </div>
                        <div className="form-outline mb-4">
                          <input 
                                type="password" 
                                name="pass1"
                                className="form-control form-control-lg"
                                value={pass1}
                                onChange={(e) => handleInputChange(e, "pass1")}
                                onBlur={checkPassword}
                            />
                          <label className="form-label">Password</label>
                        </div>
                        <div className="form-outline mb-4">
                          <input 
                                type="password" 
                                name="pass2"
                                className="form-control form-control-lg"
                                value={pass2}
                                onChange={(e) => handleInputChange(e, "pass2")}
                            />
                          <label className="form-label">Repeat your password</label>
                        </div>
                        <div className="form-check d-flex justify-content-center mb-5">
                          <input className="form-check-input me-2" type="checkbox" defaultValue id="form2Example3cg" />
                          <label className="form-check-label" htmlFor="form2Example3g">
                            I agree all statements in <a href="#!" className="text-body"><u>Terms of service</u></a>
                          </label>
                        </div>
                        <div className="d-flex justify-content-center">
                          <input 
                                type="submit" 
                                defaultValue="Submit"
                                className="btn btn-success btn-block btn-lg gradient-custom-4 text-body"
                                onClick={handleSubmit}
                            />
                        </div>
                        <p className="text-center text-muted mt-5 mb-0">Have already an account? <a href="#!" className="fw-bold text-body"><u>Login here</u></a></p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
        </>
    );
}

export default Registration;
react-js\my-app\public\index.html
//react-js\my-app\public\index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
  </head>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
C:\react-js\my-app\src\App.css
.gradient-custom-3 {
  background: #84fab0;
  background: -webkit-linear-gradient(to right, rgba(132, 250, 176, 0.5), rgba(143, 211, 244, 0.5));
  background: linear-gradient(to right, rgba(132, 250, 176, 0.5), rgba(143, 211, 244, 0.5))
}
.error{
    color: red;
}
.success{
    color: green;
}
Run C:\react-j\my-app>npm start
http://localhost:3000/

PHP Mysql

http://localhost/devtest/reactjs/registration.php
http://localhost/devtest/reactjs/checkuser.php
http://localhost/devtest/reactjs/checkemail.php

Registration.php
//Registration.php
<?php

    header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
    header("Access-Control-Allow-Methods: GET, POST");
    header("Access-Control-Allow-Headers: Content-Type");

    $conn = new mysqli("localhost", "root", "", "reactjsdb");
    if(mysqli_connect_error()){
        echo mysqli_connect_error();
        exit();
    }
    else{
        $eData = file_get_contents("php://input");
        $dData = json_decode($eData, true);

        $user = $dData['user'];
        $email = $dData['email'];
        $pass = $dData['pass'];

        $result = "";

        if($user != "" and $email != "" and $pass != ""){
            $sql = "INSERT INTO user(user, email, pass) VALUES('$user', '$email', '$pass');";
            $res = mysqli_query($conn, $sql);
            if($res){
                $result = "You have registered successfully!";
            }
            else{
                $result = "";
            }
        }
        else{
            $result = "";
        }

        $conn -> close();
        $response[] = array("result" => $result);
        echo json_encode($response);
    }

?>
checkuser.php
//checkuser.php
<?php

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST");
    header("Access-Control-Allow-Headers: Content-Type");

    $conn = new mysqli("localhost", "root", "", "reactjsdb");
    if(mysqli_connect_error()){
        echo mysqli_connect_error();
        exit();
    }
    else{
        $eData = file_get_contents("php://input");
        $dData = json_decode($eData, true);

        $user = $dData['user'];

        $result = "";

        if($user != ""){
            $sql = "SELECT * FROM user WHERE user='$user';";
            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) != 0){
                $result = "Username is already taken!";
            }
            else{
                $result = "";
            }
        }
        else{
            $result = "";
        }

        $conn -> close();
        $response[] = array("result" => $result);
        echo json_encode($response);
    }

?>
checkemail.php
//checkemail.php
<?php

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST");
    header("Access-Control-Allow-Headers: Content-Type");

    $conn = new mysqli("localhost", "root", "", "reactjsdb");
    if(mysqli_connect_error()){
        echo mysqli_connect_error();
        exit();
    }
    else{
        $eData = file_get_contents("php://input");
        $dData = json_decode($eData, true);

        $email = $dData['email'];

        $result = "";

        if($email != ""){
            $sql = "SELECT * FROM user WHERE email='$email';";
            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) != 0){
                $result = "Email is already registered!";
            }
            else{
                $result = "";
            }
        }
        else{
            $result = "";
        }

        $conn -> close();
        $response[] = array("result" => $result);
        echo json_encode($response);
    }

?>

Monday, June 19, 2023

React JS Login with Protected dashboard page and PHP Mysql

React JS Login with Protected dashboard page and PHP Mysql

React JS
https://create-react-app.dev/

Create Project
C:\react-js>npx create-react-app my-app

Run
C:\react-js\my-app> npm start

C:\react-js\my-app\src\App.js
//C:\react-js\my-app\src\App.js
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Protected from "./components/Protected";
import Dashboard from "./components/Dashboard";
import Login from "./components/Login";
//import './App.css';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Login />} />
        <Route path="/dashboard" element={<Protected Component={Dashboard} />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App
Install React Router Dom
https://www.npmjs.com/package/react-router-dom
C:\react-js\myreactdev>npm i react-router-dom --save
C:\react-js\my-app\src\components\Login.js
//C:\react-js\my-app\src\components\Login.js
import React, { useState, useEffect  } from "react";

import { useNavigate } from 'react-router-dom';

export default function Login() {
    const naviget = useNavigate();
    const [user, setUser] = useState("");
    const [pass, setPass] = useState("");
    const [error, setError] = useState("");
    const [msg, setMsg] = useState("");

    useEffect(() => {
        let login = localStorage.getItem("login");
        if(login){
            naviget("/dashboard");
        }
        let loginStatus = localStorage.getItem("loginStatus");
        if(loginStatus){
            setError(loginStatus);
            setTimeout(function(){
                localStorage.clear();
                window.location.reload();
            }, 3000);
        }
        setTimeout(function(){
            setMsg("");
        }, 5000);
    }, [msg]);

    const handleInputChange = (e, type) => {
        switch(type){
            case "user":
                setError("");
                setUser(e.target.value);
                if(e.target.value === ""){
                    setError("Username has left blank");
                }
                break;
            case "pass":
                setError("");
                setPass(e.target.value);
                if(e.target.value === ""){
                    setError("Password has left blank");
                }
                break;
            default:
        }
    }

    function loginSubmit(){
        if(user !== "" && pass != ""){
            var url = "http://localhost/devtest/reactjs/login.php";
            var headers = {
                "Accept": "application/json",
                "Content-type": "application/json"
            };
            var Data = {
                user: user,
                pass: pass
            };
            fetch(url, {
                method: "POST",
                headers: headers,
                body: JSON.stringify(Data)
            }).then((response) => response.json())
            .then((response) => {
                console.log(response);
                if(response[0].result === "Invalid username!" || response[0].result === "Invalid password!"){
                    setError(response[0].result);
                }
                else{
                    setMsg(response[0].result);
                    setTimeout(function(){
                        localStorage.setItem("login", true);
                        localStorage.setItem('user', user);
                        naviget("/dashboard");
                    }, 5000);
                }
            }).catch((err) => {
                setError(err);
                console.log(err);
            })
        }
        else{
            setError("All field are required!")
        }
    }
    return(
        <>
        <section className="vh-100" style={{backgroundColor: '#9A616D'}}>
        <div className="container py-5 h-100">
            <div className="row d-flex justify-content-center align-items-center h-100">
            <div className="col col-xl-10">
                <div className="card" style={{borderRadius: '1rem'}}>
                <div className="row g-0">
                    <div className="col-md-6 col-lg-5 d-none d-md-block">
                    <img src="https://images.pexels.com/photos/4348403/pexels-photo-4348403.jpeg?auto=compress&cs=tinysrgb&w=1600" alt="login form" className="img-fluid" style={{borderRadius: '1rem 0 0 1rem'}} />
                    </div>
                    <div className="col-md-6 col-lg-7 d-flex align-items-center">
                    <div className="card-body p-4 p-lg-5 text-black">
                        <p>
                            {
                                error !== "" ?
                                <div style={{color: '#842029'}}><b>{error}</b></div> :
                                <div style={{color: '#badbcc'}}><b>{msg}</b></div>
                            }
                        </p>
                        <div className="d-flex align-items-center mb-3 pb-1">
                            <i className="fas fa-cubes fa-2x me-3" style={{color: '#ff6219'}} />
                            <span className="h1 fw-bold mb-0">Logo</span>
                        </div>
                        <h5 className="fw-normal mb-3 pb-3" style={{letterSpacing: 1}}>Sign into your account</h5>
                        <div className="form-outline mb-4">
                            <input 
                                type="text" 
                                id="username"
                                className="form-control form-control-lg"
                                value={user}
                                onChange={(e) => handleInputChange(e, "user")}
                            />
                            <label className="form-label" htmlFor="username">User Name</label>
                        </div>
                        <div className="form-outline mb-4">
                            <input 
                                type="password" 
                                id="pass"
                                className="form-control form-control-lg"
                                value={pass}
                                onChange={(e) => handleInputChange(e, "pass")}
                            />
                            <label className="form-label" htmlFor="pass">Password</label>
                        </div>
                        <div className="pt-1 mb-4">
                            <input 
                                type="submit"
                                defaultValue="Login" 
                                className="btn btn-dark btn-lg btn-block"
                                onClick={loginSubmit}
                            />
                        </div>
                        <a className="small text-muted" href="#!">Forgot password?</a>
                        <p className="mb-5 pb-lg-2" style={{color: '#393f81'}}>Don't have an account? <a href="#!" style={{color: '#393f81'}}>Register here</a></p>
                        <a href="#!" className="small text-muted">Terms of use.</a>
                        <a href="#!" className="small text-muted">Privacy policy</a>
                    </div>
                    </div>
                </div>
                </div>
            </div>
            </div>
        </div>
        </section>
        </>
    )
}
C:\react-js\my-app\src\components\Dashboard.js
//C:\react-js\my-app\src\components\Dashboard.js
import React, {  } from "react";
import { useNavigate } from 'react-router-dom';

export default function Dashboard() {
    const naviget = useNavigate();
    function logoutSubmit(){
        localStorage.setItem("login", "");
        localStorage.setItem("loginStatus", "Logged out successfully!")
        naviget("/");
    }
    const user = localStorage.getItem('user');
    return(
        <>
        <nav className="navbar navbar-expand-lg navbar-light bg-light">
        <div className="container">
          <a className="navbar-brand" href="#">Cairocoders</a>
          <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span className="navbar-toggler-icon" />
          </button>
          <div className="collapse navbar-collapse" id="navbarSupportedContent">
            <ul className="navbar-nav me-auto mb-2 mb-lg-0">
              <li className="nav-item">
                <a className="nav-link active" aria-current="page" href="#">Home</a>
              </li>
              <li className="nav-item">
                <a className="nav-link" href="#">Link</a>
              </li>
            </ul>
            <div className="d-flex">
              <button className="btn btn-outline-primary" type="submit" onClick={logoutSubmit}>
                Logout
              </button>
            </div>
          </div>
        </div>
        </nav>
        <div className="container" style={{paddingTop: 50}}>
            <h3>{user}</h3>
            <h3>Dashboard Page</h3>
        </div>
        </>
    )
}
C:\react-js\my-app\src\components\Protected.js
//C:\react-js\my-app\src\components\Protected.js
import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";

export default function Protected(props) {
    const naviget = useNavigate();
    const { Component } = props;
    useEffect(() => {
        let login = localStorage.getItem("login");
        if(!login){
            localStorage.setItem("loginStatus", "Please login to view dashboard!");
            naviget("/", {replace: true});
        }
    }, []);

    return(
        <Component />
    );
}
react-js\my-app\public\index.html
//react-js\my-app\public\index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
Run C:\react-j\myreactdev>npm start
http://localhost:3000/

PHP Mysql http://localhost/devtest/reactjs/login.php
//http://localhost/devtest/reactjs/login.php
<?php
	header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
    header("Access-Control-Allow-Methods: GET, POST");
    header("Access-Control-Allow-Headers: Content-Type");

    $conn = new mysqli("localhost", "root", "", "reactjsDB");
    if(mysqli_connect_error()){
        echo mysqli_connect_error();
        exit();
    }
    else{
        $eData = file_get_contents("php://input");
        $dData = json_decode($eData, true);

        $user = $dData['user'];
        $pass = $dData['pass'];
		//$password = md5($pass);
        $result = "";

        if($user != "" and $pass != ""){
            $sql = "SELECT * FROM user WHERE user='$user';";
            $res = mysqli_query($conn, $sql);

            if(mysqli_num_rows($res) != 0){
                $row = mysqli_fetch_array($res);
                if($pass != $row['pass']){
                    $result = "Invalid password!";
                }
                else{
                    $result = "Loggedin successfully! Redirecting...";
                }
            }
            else{
                $result = "Invalid username!";
            }
        }
        else{
            $result = "";
        }

        $conn -> close();
        $response[] = array("result" => $result);
        echo json_encode($response);
    }

?>

Tuesday, February 21, 2023

PHP Mysql PDO CRUD Server Side Ajax DataTables

PHP Mysql PDO CRUD Server Side Ajax DataTables

Create database table 
CREATE TABLE `member` (
  `id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `phone` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

datatables
https://datatables.net/
Add advanced interaction controls
to your HTML tables the free & easy way
index.php
//index.php
<!doctype html>
<head>
    <title>PHP Mysql PDO CRUD Server Side Ajax DataTables</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container">
    <br />
    <h3 align="center">PHP Mysql PDO CRUD Server Side Ajax DataTables</h3>   
    <br />
    <div align="right">
		<button type="button" id="add_button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal">
		  Add Member
		</button>
    </div>
    <br />	
    <table id="member_table" class="table table-striped">  
        <thead bgcolor="#6cd8dc">
            <tr class="table-primary">
                <th width="30%">ID</th>
                <th width="50%">Name</th>  
                <th width="30%">Email</th>
                <th width="30%">Phone</th>
                <th scope="col" width="5%">Edit</th>
                <th scope="col" width="5%">Delete</th>
            </tr>
        </thead>
    </table>
	
	<div class="modal" id="userModal" tabindex="-1">
	  <div class="modal-dialog">
		<div class="modal-content">
		  <div class="modal-header">
			<h5 class="modal-title">Add Member</h5>
			<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
		  </div>
		  <div class="modal-body">
			<form method="post" id="member_form" enctype="multipart/form-data">
				<div class="modal-body">
					<label>Enter Name</label>
					<input type="text" name="name" id="name" class="form-control" />
					<br />
					<label>Enter Email</label>
					<input type="email" name="email" id="email" class="form-control" />
					<br /> 
					<label>Enter Phone</label>
					<input type="text" name="phone" id="phone" class="form-control" />
					<br /> 
				</div>
				<div class="modal-footer">
					<input type="hidden" name="member_id" id="member_id" />
					<input type="hidden" name="operation" id="operation" />
					<input type="submit" name="action" id="action" class="btn btn-primary" value="Add" />
					<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
				</div>
			</form>
		  </div>
		</div>
	  </div>
	</div>
</div>  
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    $('#add_button').click(function(){
        $('#member_form')[0].reset();
        $('.modal-title').text("Add New Details");
        $('#action').val("Add");
        $('#operation').val("Add");
    });
    
    var dataTable = $('#member_table').DataTable({
        "paging":true,
        "processing":true,
        "serverSide":true,
        "order": [],
        "info":true,
        "ajax":{
            url:"fetch.php",
            type:"POST"
               },
        "columnDefs":[
            {
                "targets":[0,3,4],
                "orderable":false,
            },
        ],    
    });

    $(document).on('submit', '#member_form', function(event){
        event.preventDefault();
        var id = $('#id').val();
        var name = $('#name').val();
        var email = $('#email').val();
        
        if(name != '' && email != '')
        {
            $.ajax({
                url:"insertupdated.php",
                method:'POST',
                data:new FormData(this),
                contentType:false,
                processData:false,
                success:function(data)
                {
                    $('#member_form')[0].reset();
                    $('#userModal').modal('hide');
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            alert("Name, email Fields are Required");
        }
    });
    
    $(document).on('click', '.update', function(){
        var member_id = $(this).attr("id");
        $.ajax({
            url:"fetch_single.php",
            method:"POST",
            data:{member_id:member_id},
            dataType:"json",
            success:function(data)
            {
                $('#userModal').modal('show');
                $('#id').val(data.id);
                $('#name').val(data.name);
                $('#email').val(data.email);
                $('#phone').val(data.phone);
                $('.modal-title').text("Edit Member Details");
                $('#member_id').val(member_id);
                $('#action').val("Save");
                $('#operation').val("Edit");
            }
        })
    });
    
    $(document).on('click', '.delete', function(){
        var member_id = $(this).attr("id");
        if(confirm("Are you sure you want to delete this user?"))
        {
            $.ajax({
                url:"delete.php",
                method:"POST",
                data:{member_id:member_id},
                success:function(data)
                {
                    dataTable.ajax.reload();
                }
            });
        }
        else
        {
            return false;   
        }
    });
    
    
});
</script>             
</body>
</html>
db.php
//db.php
<?php
$connection = new PDO( 'mysql:host=localhost;dbname=projectdb', 'root', '' );
?>
//fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM member ";
if(isset($_POST["search"]["value"]))
{
	$query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR email LIKE "%'.$_POST["search"]["value"].'%" ';
} 

if(isset($_POST["order"]))
{
	$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
	$query .= 'ORDER BY id ASC ';
}

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)
{
	$sub_array = array();
	
	$sub_array[] = $row["id"];
	$sub_array[] = $row["name"];
	$sub_array[] = $row["email"];
	$sub_array[] = $row["phone"];
	$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-primary btn-sm update"><i class="glyphicon glyphicon-pencil"> </i>Edit</button></button>';
	$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-sm delete">Delete</button>';
	$data[] = $sub_array;
}
$output = array(
	"draw"				=>	intval($_POST["draw"]),
	"recordsTotal"		=> 	$filtered_rows,
	"recordsFiltered"	=>	get_total_all_records(),
	"data"				=>	$data
);
echo json_encode($output);
?>
function.php
//function.php
<?php
function get_total_all_records()
{
	include('db.php');
	$statement = $connection->prepare("SELECT * FROM member");
	$statement->execute();
	$result = $statement->fetchAll();
	return $statement->rowCount();
}
?>
insertupdated.php
//insertupdated.php
<?php
include('db.php');
include('function.php');
if(isset($_POST["operation"]))
{
	if($_POST["operation"] == "Add")
	{
		$statement = $connection->prepare("
			INSERT INTO member (name, email, phone) VALUES (:name, :email, :phone)");
		$result = $statement->execute(
			array(
				':name'	=>	$_POST["name"],
				':email'	=>	$_POST["email"],
				':phone'	=>	$_POST["phone"]
			)
		);
	}
	if($_POST["operation"] == "Edit")
	{
		$statement = $connection->prepare(
			"UPDATE member
			SET name = :name, email = :email, phone = :phone WHERE id = :id");
		$result = $statement->execute(
			array(
				':name'	=>	$_POST["name"],
				':email'	=>	$_POST["email"],
				':phone'	=>	$_POST["phone"],
				':id'			=>	$_POST["member_id"]
			)
		);
	}
}
?>
fetch_single.php
//fetch_single.php
<?php
include('db.php');
include('function.php');
if(isset($_POST["member_id"]))
{
	$output = array();
	$statement = $connection->prepare(
		"SELECT * FROM member WHERE id = '".$_POST["member_id"]."' LIMIT 1"
	);
	$statement->execute();
	$result = $statement->fetchAll();
	foreach($result as $row)
	{
		$output["id"] = $row["id"];
		$output["name"] = $row["name"];
		$output["email"] = $row["email"];
		$output["phone"] = $row["phone"];
	}
	echo json_encode($output);
}
?>
delete.php
//delete.php
<?php
include('db.php');
include('function.php');

if(isset($_POST["member_id"]))
{
	$statement = $connection->prepare(
		"DELETE FROM member WHERE id = :id"
	);
	$result = $statement->execute(

		array(':id'	=>	$_POST["member_id"])
		
	    );
}
?>

Related Post