article

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

Wednesday, February 15, 2023

PHP MySQL Ajax Live Search

PHP MySQL Ajax Live Search

Database table

CREATE TABLE `users` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

database connection
dbcon.php
//dbcon.php
<?php 
$conn = mysqli_connect("localhost","root","","projectdb");
 
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}
?>
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.6.0/dist/jquery.min.js

index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP MySQL Ajax Live Search</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <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.6.0/dist/jquery.min.js"></script>
</head>
<body>
<?php
include('dbcon.php')
?>
<div class="container mt-4">
	<p><h2>PHP MySQL Ajax Live Search</h2></p>
	<h6 class="mt-5"><b>Search Name</b></h6>
    <div class="input-group mb-4 mt-3">
		 <div class="form-outline">
			<input type="text" id="getName"/>
		</div>
	</div>                   
	<table class="table table-striped">
		<thead>
		  <tr>
			<th>ID</th>
			<th>Name</th>
			<th>Email</th>
		  </tr>
		</thead>
		<tbody id="showdata">
		  <?php  
				$sql = "SELECT * FROM users";
				$query = mysqli_query($conn,$sql);
				while($row = mysqli_fetch_assoc($query))
				{
				  echo"<tr>";
				   echo"<td><h6>".$row['id']."</h6></td>";
				   echo"<td><h6>".$row['name']."</h6></td>";
				   echo"<td>".$row['email']."</td>";
				  echo"</tr>";   
				}
			?>
		</tbody>
	</table>
</div>
<script>
  $(document).ready(function(){
   $('#getName').on("keyup", function(){
     var getName = $(this).val();
     $.ajax({
       method:'POST',
       url:'searchajax.php',
       data:{name:getName},
       success:function(response)
       {
            $("#showdata").html(response);
       } 
     });
   });
  });
</script>
</body>
</html>
search request
searchajax.php
//
<?php 
  include("dbcon.php");
 
   $name = $_POST['name'];
 
   $sql = "SELECT * FROM users WHERE name LIKE '$name%'";  
   $query = mysqli_query($conn,$sql);
   $data='';
   while($row = mysqli_fetch_assoc($query))
   {
       $data .=  "<tr><td>".$row['id']."</td><td>".$row['name']."</td><td>".$row['email']."</td></tr>";
   }
    echo $data;
 ?>

Thursday, July 28, 2022

PHP MySQLi Shopping Cart Using Jquery Ajax

PHP MySQLi Shopping Cart Using Jquery Ajax

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

Crate Database Table 

CREATE TABLE `product` (
  `id` int(11) NOT NULL,
  `product_name` varchar(255) NOT NULL,
  `product_price` varchar(100) NOT NULL,
  `product_qty` int(11) NOT NULL DEFAULT 1,
  `product_image` varchar(255) NOT NULL,
  `product_code` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `product` (`id`, `product_name`, `product_price`, `product_qty`, `product_image`, `product_code`) VALUES
(1, 'HUAWEI Matebook D 14 Laptop', '25999', 1, 'image/01.jpg', 'p1000'),
(2, 'Lenovo IdeaPad Gaming 3', '38780', 1, 'image/02.jpg', 'p1001'),
(3, 'HP Laptop 6570B/450/650', '13562', 1, 'image/03.jpg', 'p1002'),
(4, 'Infinix INbook X1, Core i3-1005G1', '20999', 1, 'image/04.jpg', 'p1003');

CREATE TABLE `cart` (
  `id` int(11) NOT NULL,
  `product_name` varchar(100) NOT NULL,
  `product_price` varchar(50) NOT NULL,
  `product_image` varchar(255) NOT NULL,
  `qty` int(10) NOT NULL,
  `total_price` varchar(100) NOT NULL,
  `product_code` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `address` varchar(255) NOT NULL,
  `pmode` varchar(50) NOT NULL,
  `products` varchar(255) NOT NULL,
  `amount_paid` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
index.php
//index.php
<?php include 'header.php'; ?>
  <div class="container">
  <p><h1>PHP MySQLi Shopping Cart Using Jquery Ajax</h1></p>
    <div class="row mt-2 pb-3">
      <?php
  			include 'config.php';
  			$stmt = $conn->prepare('SELECT * FROM product');
  			$stmt->execute();
  			$result = $stmt->get_result();
  			while ($row = $result->fetch_assoc()):
  		?>
      <div class="col-sm-6 col-md-4 col-lg-3 mb-2">
        <div class="card-deck">
          <div class="card p-2 border-secondary mb-2">
            <img src="<?php echo $row['product_image']; ?>" class="card-img-top" height="250">
            <div class="card-body p-1">
              <h4 class="card-title text-center text-info"><?php echo $row['product_name']; ?></h4>
              <h5 class="card-text text-center text-danger">  <?php echo number_format($row['product_price'],2); ?></h5>

            </div>
            <div class="card-footer p-1">
                <a href="details.php?item=<?php echo $row['id']; ?>" class="btn btn-primary"><i class="fas fa-cart-plus"></i>  Buy Now</a>
            </div>
          </div>
        </div>
      </div>
      <?php endwhile; ?>
    </div>
  </div>
<?php include 'footer.php'; ?>
header.php
//header.php
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>PHP MySQLi Shopping Cart Using Ajax</title>
  <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css' />
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css' />
</head>
<body>
  <nav class="navbar navbar-expand-md bg-primary navbar-dark">
    <a class="navbar-brand" href="index.php">  Cairocoders</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item">
          <a class="nav-link active" href="index.php">Products</a>
        </li>
		<li class="nav-item"><a class="nav-link active" href="login.php">Login</a></li>
		<li class="nav-item"><a class="nav-link active" href="sign.php">Sign Up</a></li>
        <li class="nav-item">
          <a class="nav-link" href="cart.php"><i class="fas fa-shopping-cart"></i> <span id="cart-item" class="badge badge-danger"></span></a>
        </li>
      </ul>
    </div>
  </nav>
footer.php
//footer.php
<script src='https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js'></script>
<script src='script.js'></script>
</body>
</html>
config.php
//config.php
<?php
	$conn = new mysqli("localhost","root","","projectdb");
	if($conn->connect_error){
		die("Connection Failed!".$conn->connect_error);
	}
?>
cart.php
//cart.php
<?php 
include 'header.php'; 
session_start();
?>
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-lg-10">
        <div style="display:<?php if (isset($_SESSION['showAlert'])) {
  echo $_SESSION['showAlert'];
} else {
  echo 'none';
} unset($_SESSION['showAlert']); ?>" class="alert alert-success alert-dismissible mt-3">
          <button type="button" class="close" data-dismiss="alert">×</button>
          <strong><?php if (isset($_SESSION['message'])) {
  echo $_SESSION['message'];
} unset($_SESSION['showAlert']); ?></strong>
        </div>
        <div class="table-responsive mt-2">
          <table class="table table-bordered table-striped text-center">
            <thead>
              <tr>
                <td colspan="7">
                  <h4 class="text-center text-info m-0">Products in your cart!</h4>
                </td>
              </tr>
              <tr>
                <th>ID</th>
                <th>Image</th>
                <th>Product</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Total Price</th>
                <th>
                  <a href="action.php?clear=all" class="badge-danger badge p-1" onclick="return confirm('Are you sure want to clear your cart?');"><i class="fas fa-trash"></i>  Clear Cart</a>
                </th>
              </tr>
            </thead>
            <tbody>
              <?php
                require 'config.php';
                $stmt = $conn->prepare('SELECT * FROM cart');
                $stmt->execute();
                $result = $stmt->get_result();
                $grand_total = 0;
                while ($row = $result->fetch_assoc()):
              ?>
              <tr>
                <td><?php echo $row['id']; ?></td>
                <input type="hidden" class="pid" value="<?php echo $row['id']; ?>">
                <td><img src="<?php echo $row['product_image']; ?>" width="50"></td>
                <td><?php echo $row['product_name']; ?></td>
                <td><?php echo number_format($row['product_price'],2); ?></td>
					<input type="hidden" class="pprice" value="<?php echo $row['product_price'];?>">
                <td><input type="number" class="form-control itemQty" value="<?php echo $row['qty']; ?>" style="width:75px;"></td>
                <td><?php echo number_format($row['total_price'],2); ?></td>
                <td>
                  <a href="action.php?remove=<?php echo $row['id']; ?>" class="text-danger lead" onclick="return confirm('Are you sure want to remove this item?');"><i class="fas fa-trash-alt"></i></a>
                </td>
              </tr>
              <?php $grand_total += $row['total_price']; ?>
              <?php endwhile; ?>
              <tr>
                <td colspan="3">
                  <a href="index.php" class="btn btn-success"><i class="fas fa-cart-plus"></i>  Continue Shopping</a>
                </td>
                <td colspan="2"><b>Grand Total</b></td>
                <td><b><?php echo number_format($grand_total,2); ?></b></td>
                <td>
                  <a href="checkout.php" class="btn btn-info <?php echo ($grand_total > 1) ? '' : 'disabled'; ?>"><i class="far fa-credit-card"></i>  Checkout</a>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
<?php include 'footer.php'; ?>
checkout.php
//checkout.php
<?php 
include 'header.php'; 
require 'config.php';

	$grand_total = 0;
	$allItems = '';
	$items = [];

	$sql = "SELECT CONCAT(product_name, '(',qty,')') AS ItemQty, total_price FROM cart";
	$stmt = $conn->prepare($sql);
	$stmt->execute();
	$result = $stmt->get_result();
	while ($row = $result->fetch_assoc()) {
	  $grand_total += $row['total_price'];
	  $items[] = $row['ItemQty'];
	}
	$allItems = implode(', ', $items);
?>
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-lg-6 px-4 pb-4" id="order">
        <h4 class="text-center text-success p-2">Complete your order!</h4>
        <div class="jumbotron p-3 mb-2 text-center">
          <h6 class="lead"><b>Product(s) : </b><?= $allItems; ?></h6>
          <h6 class="lead"><b>Delivery Charge : </b>Free</h6>
          <h5><b>Total Amount Payable : </b><?= number_format($grand_total,2) ?>/-</h5>
        </div>
        <form action="" method="post" id="placeOrder">
          <input type="hidden" name="products" value="<?= $allItems; ?>">
          <input type="hidden" name="grand_total" value="<?= $grand_total; ?>">
          <div class="form-group">
            <input type="text" name="name" class="form-control" placeholder="Enter Name" required>
          </div>
          <div class="form-group">
            <input type="email" name="email" class="form-control" placeholder="Enter E-Mail" required>
          </div>
          <div class="form-group">
            <input type="tel" name="phone" class="form-control" placeholder="Enter Phone" required>
          </div>
          <div class="form-group">
            <textarea name="address" class="form-control" rows="3" cols="10" placeholder="Enter Delivery Address Here..."></textarea>
          </div>
          <h6 class="text-center lead">Select Payment Mode</h6>
          <div class="form-group">
            <select name="pmode" class="form-control">
              <option value="" selected disabled>-Select Payment Mode-</option>
              <option value="cod">Cash On Delivery</option>
              <option value="netbanking">Net Banking</option>
              <option value="cards">Debit/Credit Card</option>
            </select>
          </div>
          <div class="form-group">
            <input type="submit" name="submit" value="Place Order" class="btn btn-success btn-block">
          </div>
        </form>
      </div>
    </div>
  </div>
<?php include 'footer.php'; ?>
details.php
//details.php
<?php include 'header.php'; ?>
  <div class="container">
  <p><h1>PHP MySQLi Shopping Cart Using Jquery Ajax</h1></p>
    <div id="message"></div>
    <div class="row mt-2 pb-3">
      <?php
  			include 'config.php';
			$id = $_GET['item'];
  			$stmt = $conn->prepare('SELECT * FROM product WHERE id=?');
			$stmt->bind_param('i',$id);
  			$stmt->execute();
  			$result = $stmt->get_result();
  			while ($row = $result->fetch_assoc()):
  		?>
      <div class="col-sm-4">
           <img src="<?php echo $row['product_image']; ?>">
      </div>
		<div class="col-sm-8">
            <form action="" class="form-submit">
				<h4 class="card-title text-info"><?php echo $row['product_name']; ?></h4>
				<h5 class="card-text text-danger">  <?php echo number_format($row['product_price'],2); ?></h5>
                <div class="row p-2">
                  <div class="col-md-6 py-1 pl-4">
                    <b>Quantity : </b>
                  </div>
                  <div class="col-md-6">
                    <input type="number" class="form-control pqty" value="<?php echo $row['product_qty']; ?>">
                  </div>
                </div>
                <input type="hidden" class="pid" value="<?php echo $row['id']; ?>">
                <input type="hidden" class="pname" value="<?php echo $row['product_name']; ?>">
                <input type="hidden" class="pprice" value="<?php echo $row['product_price']; ?>">
                <input type="hidden" class="pimage" value="<?php echo $row['product_image']; ?>">
                <input type="hidden" class="pcode" value="<?php echo $row['product_code']; ?>">
                <button class="btn btn-primary btn-block addItemBtn"><i class="fas fa-cart-plus"></i>  Add to cart</button>
            </form>
			<p><h5>Product Specifications</h5></p>
			<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>
		</div>
      <?php endwhile; ?>
    </div>
  </div>
<?php include 'footer.php'; ?>
action.php
//action.php
<?php
	session_start();
	require 'config.php';

	if (isset($_POST['pid'])) {
	  $pid = $_POST['pid'];
	  $pname = $_POST['pname'];
	  $pprice = $_POST['pprice'];
	  $pimage = $_POST['pimage'];
	  $pcode = $_POST['pcode'];
	  $pqty = $_POST['pqty'];
	  $total_price = $pprice * $pqty;

	  $stmt = $conn->prepare('SELECT product_code FROM cart WHERE product_code=?');
	  $stmt->bind_param('s',$pcode);
	  $stmt->execute();
	  $res = $stmt->get_result();
	  $r = $res->fetch_assoc();
	  $code = $r['product_code'] ?? '';

	  if (!$code) {
	    $query = $conn->prepare('INSERT INTO cart (product_name,product_price,product_image,qty,total_price,product_code) VALUES (?,?,?,?,?,?)');
	    $query->bind_param('ssssss',$pname,$pprice,$pimage,$pqty,$total_price,$pcode);
	    $query->execute();

	    echo '<div class="alert alert-success alert-dismissible mt-2">
						  <strong>Item added to your cart!</strong>
						</div>';
	  } else {
	    echo '<div class="alert alert-danger alert-dismissible mt-2">
						  <strong>Item already added to your cart!</strong>
						</div>';
	  }
	}

	// Get no.of items available in the cart table
	if (isset($_GET['cartItem']) && isset($_GET['cartItem']) == 'cart_item') {
	  $stmt = $conn->prepare('SELECT * FROM cart');
	  $stmt->execute();
	  $stmt->store_result();
	  $rows = $stmt->num_rows;

	  echo $rows;
	}

	// Remove single items from cart
	if (isset($_GET['remove'])) {
	  $id = $_GET['remove'];

	  $stmt = $conn->prepare('DELETE FROM cart WHERE id=?');
	  $stmt->bind_param('i',$id);
	  $stmt->execute();

	  $_SESSION['showAlert'] = 'block';
	  $_SESSION['message'] = 'Item removed from the cart!';
	  header('location:cart.php');
	}

	// Remove all items at once from cart
	if (isset($_GET['clear'])) {
	  $stmt = $conn->prepare('DELETE FROM cart');
	  $stmt->execute();
	  $_SESSION['showAlert'] = 'block';
	  $_SESSION['message'] = 'All Item removed from the cart!';
	  header('location:cart.php');
	}

	// Checkout and save customer info in the orders table
	if (isset($_POST['action']) && isset($_POST['action']) == 'order') {
	  $name = $_POST['name'];
	  $email = $_POST['email'];
	  $phone = $_POST['phone'];
	  $products = $_POST['products'];
	  $grand_total = $_POST['grand_total'];
	  $address = $_POST['address'];
	  $pmode = $_POST['pmode'];

	  $data = '';

	  $stmt = $conn->prepare('INSERT INTO orders (name,email,phone,address,pmode,products,amount_paid)VALUES(?,?,?,?,?,?,?)');
	  $stmt->bind_param('sssssss',$name,$email,$phone,$address,$pmode,$products,$grand_total);
	  $stmt->execute();
	  $stmt2 = $conn->prepare('DELETE FROM cart');
	  $stmt2->execute();
	  $data .= '<div class="text-center">
								<h1 class="display-4 mt-2 text-success">Thank You!</h1>
								<h2 class="text-success">Your Order Placed Successfully!</h2>
								<h4 class="bg-success text-light rounded p-2">Items Purchased : ' . $products . '</h4>
								<h4>Your Name : ' . $name . '</h4>
								<h4>Your E-mail : ' . $email . '</h4>
								<h4>Your Phone : ' . $phone . '</h4>
								<h4>Total Amount Paid : ' . number_format($grand_total,2) . '</h4>
								<h4>Payment Mode : ' . $pmode . '</h4>
						  </div>';
	  echo $data;
	}
?>
update.php
//update.php
<?php
	session_start();
	require 'config.php';

	// Set total price of the product in the cart table
	if (isset($_POST['qty'])) {
	  $qty = $_POST['qty'];
	  $pid = $_POST['pid'];
	  $pprice = $_POST['pprice'];

	  $tprice = $qty * $pprice;

	  $stmt = $conn->prepare('UPDATE cart SET qty=?, total_price=? WHERE id=?');
	  $stmt->bind_param('isi',$qty,$tprice,$pid);
	  $stmt->execute();
	} 

?>
script.js
//script.js
$(document).ready(function() {
    $(".addItemBtn").click(function(e) {
      e.preventDefault();
      var $form = $(this).closest(".form-submit");
      var pid = $form.find(".pid").val();
      var pname = $form.find(".pname").val();
      var pprice = $form.find(".pprice").val();
      var pimage = $form.find(".pimage").val();
      var pcode = $form.find(".pcode").val();

      var pqty = $form.find(".pqty").val();

      $.ajax({
        url: 'action.php',
        method: 'post',
        data: {
          pid: pid,
          pname: pname,
          pprice: pprice,
          pqty: pqty,
          pimage: pimage,
          pcode: pcode
        },
        success: function(response) {
          $("#message").html(response);
          window.scrollTo(0, 0);
          load_cart_item_number();
        }
      });
    });

    // Change the item quantity
    $(".itemQty").on('change', function() {
      var $el = $(this).closest('tr');

      var pid = $el.find(".pid").val();
      var pprice = $el.find(".pprice").val();
      var qty = $el.find(".itemQty").val(); //alert(qty);
      //location.reload(true);
      $.ajax({
        url: 'update.php',
        method: 'post',
        cache: false,
        data: {
          qty: qty,
          pid: pid,
          pprice: pprice
        },
        success: function(response) {
          console.log(response);
		  location.reload(true);
        }
      });
    });
	
    $("#placeOrder").submit(function(e) {
      e.preventDefault();
      $.ajax({
        url: 'action.php',
        method: 'post',
        data: $('form').serialize() + "&action=order",
        success: function(response) {
          $("#order").html(response);
        }
      });
    });
	
    // Load total no.of items added in the cart and display in the navbar
    load_cart_item_number();

    function load_cart_item_number() {
      $.ajax({
        url: 'action.php',
        method: 'get',
        data: {
          cartItem: "cart_item"
        },
        success: function(response) {
          $("#cart-item").html(response);
        }
      });
    }
	
});

Tuesday, July 12, 2022

PHP Mysqli Highlight Deleted Row using Jquery AJAX

PHP Mysqli Highlight Deleted Row using 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.6.0/dist/jquery.min.js
https://icons.getbootstrap.com/#install

https://datatables.net/

CREATE TABLE `users` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Mysqli Highlight Deleted Row using Jquery AJAX</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.3/font/bootstrap-icons.css">
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" />
  <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container">
	<div class="row">
		<h4>PHP Mysqli Highlight Deleted Row using Jquery AJAX</h4>
		<div class="col-sm-10">
		<table class="table table-striped table-bordered" id="user_datatable"> 
			<thead>
			<tr>
				<th>Id</th>
				<th>Name</th>
				<th>Email</th>
				<th>Action</th>
			</tr>
			</thead>
			<tbody>
			<?php
				$conn = mysqli_connect('localhost','root','','projectdb');
	 
				$sql_select = "SELECT * FROM users";
				 
				$sel_query =  mysqli_query($conn,$sql_select);
				 
				while($row = mysqli_fetch_array($sel_query))
				{
					echo'<tr id="'.$row['id'].'">';
					 echo'<td>'.$row['id'].'</td>';
					 echo'<td>'.$row['name'].'</td>';
					 echo'<td>'.$row['email'].'</td>';
					 echo'<td> <button  class="remove" name="remove" id="'.$row['id'].'"><i class="bi bi-backspace-reverse-fill" style="color:red;"></i></button></td>';
					echo'</tr>';
				}
				?>
				 
			</tbody>
		</table>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
    
	$('#user_datatable').DataTable();
	
    $('.remove').click(function(){
  
        var userID = $(this).attr('id');
          alert(userID)
         
            $.ajax({
            type: "POST",
            url: "delete.php",
            data: {deleteID:userID},
            success: function(data)
                {
                    if(confirm('Are you sure you want to delete this?'))
                    {
                       
                       $('#' + userID).css("background-color", "palegreen");
                        setTimeout(function() {
                          $('#' + userID).remove();
                        },500);
                    }   
                }
            });
        // }
       });
});
</script> 
</body>
</html>
delete.php
//delete.php
<?php
    $conn = mysqli_connect('localhost','root','','projectdb');
 
    $deleteID = $_POST['deleteID'];
 
    $sql_select = "DELETE FROM users WHERE id = $deleteID";
    $sel_query =  mysqli_query($conn,$sql_select);
     
    if($sel_query)
    {
        echo "Success";
    }
    else
    {
        echo "Error";
    }
?>

Wednesday, July 6, 2022

PHP Mysqli Login and Sign Up using jQuery Ajax

PHP Mysqli Login and Sign Up using 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.6.0/dist/jquery.min.js

CREATE TABLE `user` (
  `userid` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user` (`userid`, `username`, `password`) VALUES
(1, 'cairocoders', '25f9e794323b453885f5181f1b624d0b');

ALTER TABLE `user`
  ADD PRIMARY KEY (`userid`);

ALTER TABLE `user`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
index.php
//index.php
<?php
	session_start();
	if(isset($_SESSION['user'])){
		header('location:home.php');
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>PHP Mysqli Login and Sign Up using jQuery Ajax</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.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"/>
</head>
<body>
<p><center><h1>PHP Mysqli Login and Sign Up using jQuery Ajax </h1></center></p>
<div class="container">
	<div class="row">
		<div id="myalert" style="display:none;">
			<div class="alert alert-info">
				<center><span id="alerttext"></span></center>
			</div>
		</div>
    </div>
	
	<div class="row loginreg" id="loginform">
		<p><h1><i class="fa fa-lock" aria-hidden="true"></i> Login</h1></p>
		<form role="form" id="logform">
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fas fa-user-tie"></i></span>
				<input class="form-control" placeholder="Username" name="username" id="username" type="text" autofocus>
			</div>
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fa fa-key icon"></i></span>
				<input class="form-control" placeholder="Password" name="password" id="password" type="password">
			</div>
			<div class="checkbox">
				  <label><input type="checkbox" value=""/> Remember me</label>
			</div><br />
			<div>
				<button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block"><i class="fa fa-lock" aria-hidden="true"></i> <span id="logtext">Login</span></button>
			</div>
			
			<center><div style="border:1px solid black;height:1px;width:300px;margin-top:20px;"></div></center>
			 
			<div class="footer">
				<p>Don't have an Account! <a href="#" id="signup">Sign Up Here</a></p>
				<p>Forgot <a href="#">Password?</a></p>
			</div>
		</form>
	</div>	
	
	<div class="row loginreg" id="signupform" style="display:none;">
		<p><h1><i class="fas fa-user-tie"></i> Sign Up</h1></p>
		<form role="form" id="signform">
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fas fa-user-tie"></i></span>
				<input class="form-control" placeholder="Username" name="susername" id="susername" type="text" autofocus>
			</div>
			<div class="input-group mb-3">
				<span class="input-group-text"><i class="fa fa-key icon"></i></span>
				<input class="form-control" placeholder="Password" name="spassword" id="spassword" type="password">
			</div>
			<div>
				<button type="button" id="signupbutton" class="btn btn-lg btn-info btn-block"><i class="fa fa-lock" aria-hidden="true"></i> <span id="signtext">Sign Up</span></button>
			</div>
			
			<center><div style="border:1px solid black;height:1px;width:300px;margin-top:20px;"></div></center>
			 
			<div class="footer">
				<p>have an Account! <a href="#" id="login">Login</a></p>
				<p>Forgot <a href="#">Password?</a></p>
			</div>
		</form>
	</div>
</div>
<script src="custom.js"></script>
<style>
  .container{
        border:2px solid blue;
        text-align:center;
        
        height:500px;
        width:400px;
    }
    body{
        padding:70px;
    }
    .loginreg {
        height:90px;
        width:396px;
        background-color:paleturquoise;
    }
	.row p { 
		padding-top:10px;
	}
</style>	
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "projectdb");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
login.php
//login.php
<?php 
	include('conn.php');
	session_start();
	if(isset($_POST['username'])){
		$username=$_POST['username'];
		$password=md5($_POST['password']);

		$query=$conn->query("select * from user where username='$username' and password='$password'");

		if ($query->num_rows>0){
			$row=$query->fetch_array();
			$_SESSION['user']=$row['userid']; 
		}
		else{
			?>
  				<span>Login Failed. User not Found.</span>
  			<?php 
		}
	}
?>
signup.php
//signup.php
<?php
	include('conn.php');
	if(isset($_POST['susername'])){
		$username=$_POST['susername'];
		$password=$_POST['spassword'];

		$query=$conn->query("select * from user where username='$username'");

		if ($query->num_rows>0){
			?>
  				<span>Username already exist.</span>
  			<?php 
		}

		elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$username)){
			?>
  				<span style="font-size:11px;">Invalid username. Space & Special Characters not allowed.</span>
  			<?php 
		}
		elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$password)){
			?>
  				<span style="font-size:11px;">Invalid password. Space & Special Characters not allowed.</span>
  			<?php 
		}
		else{
			$mpassword=md5($password);
			$conn->query("insert into user (username, password) values ('$username', '$mpassword')");
			?>
  				<span>Sign up Successful.</span>
  			<?php 
		}
	}
?>
session.php
//session.php
<?php
	session_start();
	include('conn.php');

	$query=$conn->query("select * from user where userid='".$_SESSION['user']."'");
	$row=$query->fetch_array();

	$user=$row['username'];
?>
logout.php
//logout.php
<?php
	session_start();
	session_destroy();
	header('location:index.php');
?>
home.php
//home.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP Mysqli Login and Sign Up using jQuery Ajax</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<div style="height:50px;">
	</div>
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
           <h2>Welcome, <?php echo $user; ?>!</h2>
           <a href="logout.php" class="btn btn-danger"> Logout</a>
        </div>
    </div>
</div>
</body>
</html>
script.js
//script.js
$(document).ready(function(){
	//bind enter key to click button
	$(document).keypress(function(e){
    	if (e.which == 13){
    		if($('#loginform').is(":visible")){
    			$("#loginbutton").click();
    		}
        	else if($('#signupform').is(":visible")){
        		$("#signupbutton").click();
        	}
    	}
	});

	$('#signup').click(function(event){
		event.preventDefault();
		$('#loginform').slideUp();
		$('#signupform').slideDown();
		$('#myalert').slideUp();
		$('#signform')[0].reset();
	});

	$('#login').click(function(event){
		event.preventDefault();
		$('#loginform').slideDown();
		$('#signupform').slideUp();
		$('#myalert').slideUp();
		$('#logform')[0].reset();
	});

	$(document).on('click', '#signupbutton', function(){
		if($('#susername').val()!='' && $('#spassword').val()!=''){
			$('#signtext').text('Signing up...');
			$('#myalert').slideUp();
			var signform = $('#signform').serialize();
			$.ajax({
				method: 'POST',
				url: 'signup.php',
				data: signform,
				success:function(data){
					setTimeout(function(){
					$('#myalert').slideDown();
					$('#alerttext').html(data);
					$('#signtext').text('Sign up');
					$('#signform')[0].reset();
					}, 2000);
				} 
			});
		}
		else{
			alert('Please input both fields to Sign Up');
		}
	});

	$(document).on('click', '#loginbutton', function(){
		if($('#username').val()!='' && $('#password').val()!=''){
			$('#logtext').text('Logging in...');
			$('#myalert').slideUp();
			var logform = $('#logform').serialize();
			setTimeout(function(){
				$.ajax({
					method: 'POST',
					url: 'login.php',
					data: logform,
					success:function(data){
						if(data==''){
							$('#myalert').slideDown();
							$('#alerttext').text('Login Successful. User Verified!');
							$('#logtext').text('Login');
							$('#logform')[0].reset();
							setTimeout(function(){
								location.reload();
							}, 2000);
						}
						else{
							$('#myalert').slideDown();
							$('#alerttext').html(data);
							$('#logtext').text('Login');
							$('#logform')[0].reset();
						}
					} 
				});
			}, 2000);
		}
		else{
			alert('Please input both fields to Login');
		}
	});
});

Friday, June 24, 2022

PHP MySQLi Delete Table Row using Sweetalert2

PHP MySQLi Delete Table Row using Sweetalert2

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.6.0/dist/jquery.min.js

sweetalert2
https://sweetalert2.github.io/#download
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>How to Delete Table Row using Sweetalert2 with PHP/MySQLi</title>
	<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
	
	<link href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>

	<style type="text/css">
		.mt20{
			margin-top:20px;
		}
	</style>
</head>
<body>
<div class="container">
	<h1 class="text-center mt20">PHP MySQLi Delete Table Row using Sweetalert2 </h1>
	<div class="row justify-content-center">
		<div class="col-sm-8">
			<table class="table table-bordered mt20">
				<thead>
					<th>ID</th>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Address</th>
					<th>Action</th>
				</thead>
				<tbody id="tbody">
				</tbody>
			</table>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	fetch();
 
	$(document).on('click', '.btn_delete', function(){
		var id = $(this).data('id');
 
		swal.fire({
		  	title: 'Are you sure?',
		  	text: "You won't be able to revert this!",
		  	icon: 'warning',
		  	showCancelButton: true,
		  	confirmButtonColor: '#3085d6',
		  	cancelButtonColor: '#d33',
		  	confirmButtonText: 'Yes, delete it!',
		}).then((result) => {
		  	if (result.value){
		  		$.ajax({
			   		url: 'ajaxfile.php?action=delete',
			    	type: 'POST',
			       	data: 'id='+id,
			       	dataType: 'json'
			    })
			    .done(function(response){
			     	swal.fire('Deleted!', response.message, response.status);
					fetch();
			    })
			    .fail(function(){
			     	swal.fire('Oops...', 'Something went wrong with ajax !', 'error');
			    });
		  	}
 
		})
 
	});
});
 
function fetch(){
	$.ajax({
		method: 'POST',
		url: 'ajaxfile.php',
		dataType: 'json',
		success: function(response){
			$('#tbody').html(response);
		}
	});
}
</script>
</body>
</html>

Sunday, June 19, 2022

PHP Mysqli Delete Multiple Rows using jQuery Ajax

PHP Mysqli Delete Multiple Rows using 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.6.0/dist/jquery.min.js
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>PHP Mysqli Delete Multiple Rows using jQuery Ajax</title>
	<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
	<h1 class="text-center" style="margin-top:30px;">PHP Mysqli Delete Multiple Rows using jQuery Ajax</h1>
	<hr>
	<div class="row justify-content-center">
		<div class="col-8">
			<div class="alert alert-danger text-center" role="alert" style="display:none;">
				<span class="message"></span>
			</div>
			<div class="alert alert-success text-center" role="alert" style="display:none;">
				<span class="message"></span>
			</div>
			<button type="button" class="btn btn-danger" id="delete">Delete</button>
			<table class="table table-bordered" style="margin-top:15px;">
				<thead>
					<th><input type="checkbox" id="checkAll"></th>
					<th>ID</th>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Address</th>
				</thead>
				<tbody id="tbody">
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
//app.js
$(function(){
	fetch();

	//check uncheck all
	$('#checkAll').click(function () {
	    $('input:checkbox').not(this).prop('checked', this.checked);
	});

	$('#delete').click(function(){
		var ids = $(".check:checked").map(function(){
		  	return $(this).val();
		}).toArray();

		//check if a checkbox is checked
		if(jQuery.isEmptyObject(ids)){
			$('.alert').hide();
			$('.alert-danger').show();
			$('.message').html('Select row(s) to delete first');
		}
		//delete the checked rows
		else{
			$.ajax({
				type: 'POST',
				url: 'ajax.php?action=delete',
				data: {ids: ids},
				dataType: 'json',
				success: function(response){
					$('.alert').hide();
					$('.alert-success').show();
					$('.message').html(response);
					fetch();

				}
			});
		}

	});
	
});

function fetch(){
	$.ajax({
		type: 'POST',
		url: 'ajax.php',
		dataType: 'json',
		success: function(response){
			$('#tbody').html(response);
		}
	});
}
ajax.php
//ajax.php
<?php
	//connection
	$conn = new mysqli('localhost', 'root', '', 'devprojectdb');

	$action = 'fetch';
	$output = '';

	if(isset($_GET['action'])){
		$action = $_GET['action'];
	}

	if($action == 'fetch'){
		
		$sql = "SELECT * FROM members";
		$query = $conn->query($sql);

		while($row = $query->fetch_assoc()){
			$output .= "
				<tr>
					<td><input type='checkbox' class='check' value='".$row['id']."'></td>
					<td>".$row['id']."</td>
					<td>".$row['firstname']."</td>
					<td>".$row['lastname']."</td>
					<td>".$row['address']."</td>
				</tr>	
			";
		}

	}

	if($action == 'delete'){
		$output = array('error'=>false);
		$ids = $_POST['ids'];
		$count = count($ids);
		$row = ($count == 1)? 'Row' : 'Rows';

		foreach($ids as $id){
			$sql = "DELETE FROM members WHERE id = '$id'";
			$conn->query($sql);
		}
	
		$output = $count.' '.$row.' deleted';

	}

	echo json_encode($output);

?>

Friday, April 15, 2022

Crop And Upload Image using PHP and JQuery Ajax - Croppie Image Cropper

Crop And Upload Image using PHP and JQuery Ajax - Croppie Image Cropper

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.6.0/dist/jquery.min.js

Croppie
Croppie is a fast, easy to use image cropping plugin with tons of configuration options!

https://foliotek.github.io/Croppie/
https://cdnjs.com/libraries/croppie
https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css
index.php
//index.php
<html>  
  <head>  
    <title>Crop And Upload Image using PHP and JQuery Ajax - Croppie Image Cropper</title>  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
	
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> 
	<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
  </head>  
<body>  
<div class="container" style="margin-top:20px;padding:20px;">  
	<div class="card">
	  <div class="card-header">
		Crop And Upload Image using PHP and JQuery Ajax - Croppie Image Cropper
	  </div>
	  <div class="card-body">
		<h5 class="card-title">Select Image</h5>
		<input type="file" name="upload_image" id="upload_image" />       
	  </div>
	</div>

	<div class="card text-center" id="uploadimage" style='display:none'>
	  <div class="card-header">
		Upload & Crop Image
	  </div>
	  <div class="card-body">
		    <div id="image_demo" style="width:350px; margin-top:30px"></div>
            <div id="uploaded_image" style="width:350px; margin-top:30px;"></div>  
	  </div>
	  <div class="card-footer text-muted">
		<button class="crop_image">Crop & Upload Image</button>
	  </div>
	</div>
</div>
</body>  
</html>
 
<script>  
$(document).ready(function(){
 $image_crop = $('#image_demo').croppie({
    enableExif: true,
    viewport: {
      width:200,
      height:200,
      type:'circle' //circle
    },
    boundary:{
      width:300,
      height:300
    }
  });
  $('#upload_image').on('change', function(){
    var reader = new FileReader();
    reader.onload = function (event) {
      $image_crop.croppie('bind', {
        url: event.target.result
      }) 
    }
    reader.readAsDataURL(this.files[0]);
    $('#uploadimage').show();
  });
  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function(response){
      $.ajax({
        url:"upload.php",
        type: "POST",
        data:{"image": response},
        success:function(data)
        {
           $('#uploaded_image').html(data)
        }
      });
    })
  });
});  
</script>
upload.php
//upload.php
<?php
if(isset($_POST["image"]))
{
 $data = $_POST["image"];
 $image_array_1 = explode(";", $data);
 $image_array_2 = explode(",", $image_array_1[1]);
 $data = base64_decode($image_array_2[1]);
 $imageName = time() . '.png';
 file_put_contents($imageName, $data);
 echo '<img src="'.$imageName.'" class="img-thumbnail" />';
}
?>

Tuesday, April 5, 2022

Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli

Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli

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.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `multiplerow_members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `multiplerow_members` (`id`, `firstname`, `lastname`) VALUES
(1, 'Airi ', 'Sato'),
(2, 'Bourto', 'Usumaki');

ALTER TABLE `multiplerow_members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `multiplerow_members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
	<div class="row">
		<div class="col-md-12">
			<h2>Jquery Ajax Adding Multiple Rows with PHP OOP and Mysqli</h2>
			<h2>Members Table</h2>
			<div id="table"></div>
		</div>
	</div>
	<div class="row">
		<div class="col-md-8">
			<h2>Add Form</h2>
			<form id="addForm">
				<hr>
				<div class="row">
					<div class="col-md-2">
						<label style="position:relative; top:7px;">Firstname:</label>
					</div>
					<div class="col-md-10">
						<input type="text" name="firstname[]" class="form-control">
					</div>
				</div>
				<div style="height:10px;"></div>
				<div class="row">
					<div class="col-md-2">
						<label style="position:relative; top:7px;">Lastname:</label>
					</div>
					<div class="col-md-10">
						<input type="text" name="lastname[]" class="form-control">
					</div>
				</div>
				<hr>
				<div id="newrow"></div>
				<div class="row">
					<div class="col-md-12">
						<button type="button" id="save" class="btn btn-primary"> Save</button>
						<button type="button" id="newbutton" class="btn btn-primary"> Add New</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	showTable();

	$('#newbutton').click(function(){
		$('#newrow').slideDown();
		var newrow = '<hr>';
			newrow = '<div class="row">';
   		 	newrow += '<div class="col-md-2"><label style="position:relative; top:7px;">Firstname:</label></div>';
   		 	newrow += '<div class="col-md-10"><input type="text" name="firstname[]" class="form-control"></div>';
   		 	newrow += '</div>';
   		 	newrow += '<div style="height:10px;"></div>';
   		 	newrow += '<div class="row">';
   		 	newrow += '<div class="col-md-2"><label style="position:relative; top:7px;">Lastname:</label></div>';
   		 	newrow += '<div class="col-md-10"><input type="text" name="lastname[]" class="form-control"></div>';
   		 	newrow += '</div>';
   		 	newrow += '<hr>';	 	 
   		$('#newrow').append(newrow);	
	});

	$('#save').click(function(){
		var addForm = $('#addForm').serialize();
		$.ajax({
			type: 'POST',
			url: 'add.php',
			data: addForm,
			success:function(data){
				if(data==''){
					showTable();
					$('#addForm')[0].reset();
					$('#newrow').slideUp();
					$('#newrow').empty();
				}
				else{
					showTable();
					$('#addForm')[0].reset();
					$('#newrow').slideUp();
					$('#newrow').empty();
					alert('Rows with empty field are not added');
				}
				
			}
		});
	});

});

function showTable(){
	$.ajax({
		type: 'POST',
		url: 'fetch.php',
		data:{
			fetch: 1,
		},
		success:function(data){
			$('#table').html(data);
		}
	});
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
add.php
//add.php
<?php
	include('conn.php');
	if(isset($_POST['firstname'])){
		$firstname = $_POST["firstname"];
 		$lastname = $_POST["lastname"];

 		for($count = 0; $count<count($firstname); $count++){
  			$firstname_clean = mysqli_real_escape_string($conn, $firstname[$count]);
  			$lastname_clean = mysqli_real_escape_string($conn, $lastname[$count]);

  			if($firstname_clean != '' && $lastname_clean != ''){
				$conn->query("insert into multiplerow_members (firstname, lastname) values ('".$firstname_clean."', '".$lastname_clean."')");
			}
			else{
				echo "1";
			}
 		}
	}

?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		?>
			<table class="table table-bordered table-striped">
				<thead>
					<th>Firstname</th>
					<th>Lastname</th>
				</thead>
				<tbody>
					<?php
						include('conn.php');
						$query=$conn->query("select * from multiplerow_members");
						while($row=$query->fetch_array()){
							?>
							<tr>
								<td><?php echo $row['firstname']; ?></td>
								<td><?php echo $row['lastname']; ?></td>
							</tr>
							<?php
						}
					?>
				</tbody>
			</table>
		<?php
	}

?>

Saturday, April 2, 2022

Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli

Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli

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.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

ALTER TABLE `carbrands`
  ADD PRIMARY KEY (`brand_id`);

ALTER TABLE `carbrands`
  MODIFY `brand_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
  
CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');

ALTER TABLE `carmodels`
  ADD PRIMARY KEY (`model_id`),
  ADD KEY `industry_id` (`brand_id`);

ALTER TABLE `carmodels`
  MODIFY `model_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

index.php
//index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli</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.6.0/dist/jquery.min.js"></script> 
</head>
<body>
<?php
include('conn.php');
?>
<div class="container">
 <h3 class="mt-4 text-center text-secondary">Dependent Dropdown with Loading using Jquery Ajax and PHP Mysqli</h3>
  <div class="row">
    <div class="col-sm-4">

      <h5 class="mt-4">Car Brand Name</h5>
       <select name="carbrand" id="carbrand" class="form-select">
        <?php 
              $sql = "SELECT * FROM carbrands";
              $query = mysqli_query($conn,$sql);
              while($row=mysqli_fetch_assoc($query))
              {
                echo '<option value="'.$row['brand_id'].'">'.$row["brand_name"].'</option>';
              }
        ?>
       </select>
	</div>
    <div class="col-sm-4">
      <h5 class="mt-4 ">Car Model</h5>
        <p id="loading" style="display:none">
           <img src="img/loader.gif"><span class="sr-only">Loading...</span>
        </p>
        <select  class="form-select"  name="select" id="show"  style="display:none;"></select>
	</div>
</div>
</div>
<script>
  $(document).ready(function(){
    $('#carbrand').change(function(){
      var Stdid = $('#carbrand').val(); 
       $.ajax({
          url:'fetch.php',
          type:'POST',
          data:{id:Stdid},
          success:function(response)
          {
            $('#loading').css('display','block');
            setTimeout(function()
            { 
                $('#show').html(response);
                $('#show').show();
                $('#loading').css('display','none');
            },3000);
          }
       });
    });
  });
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch.php
//fetch.php
<?php
  include('conn.php');

  $id = $_POST['id'];
  $sql = "SELECT * FROM carmodels WHERE brand_id= $id ";
  $result = mysqli_query($conn,$sql);

  $out='';
  while($row = mysqli_fetch_assoc($result)) 
  {   
     $out .=  '<option>'.$row['car_models'].'</option>'; 
  }
   echo $out;
?>

Jquery Ajax Dependent Dropdown Select with PHP Mysqli

Jquery Ajax Dependent Dropdown Select with PHP Mysqli

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.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `carbrands` (
  `brand_id` int(11) NOT NULL,
  `brand_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carbrands` (`brand_id`, `brand_name`) VALUES
(1, 'Toyota'),
(2, 'Honda'),
(3, 'Suzuki'),
(4, 'Mitsubishi'),
(5, 'Hyundai');

ALTER TABLE `carbrands`
  ADD PRIMARY KEY (`brand_id`);

ALTER TABLE `carbrands`
  MODIFY `brand_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
  
CREATE TABLE `carmodels` (
  `model_id` int(11) NOT NULL,
  `brand_id` int(11) NOT NULL,
  `car_models` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `carmodels` (`model_id`, `brand_id`, `car_models`) VALUES
(1, 1, 'Toyota Corolla'),
(2, 2, 'Toyota Camry'),
(3, 1, 'Toyota Yaris'),
(4, 1, 'Toyota Sienna'),
(5, 1, 'Toyota RAV4'),
(6, 1, 'Toyota Highlander'),
(7, 2, 'Honda HR-V'),
(8, 2, 'Honda Odyssey'),
(9, 3, 'Swift'),
(10, 3, 'Celerio'),
(11, 3, 'Ertiga'),
(12, 3, 'Vitara'),
(13, 4, 'Mirage'),
(14, 4, 'Mirage G4'),
(15, 4, 'Xpander Cross'),
(16, 4, 'Montero Sport'),
(17, 4, 'Strada Athlete'),
(18, 5, 'Reina '),
(19, 5, 'Accent'),
(20, 5, 'Elantra'),
(21, 5, 'Tucson');

ALTER TABLE `carmodels`
  ADD PRIMARY KEY (`model_id`),
  ADD KEY `industry_id` (`brand_id`);

ALTER TABLE `carmodels`
  MODIFY `model_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;


index.php
//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">
    <title>Jquery Ajax Dependent Dropdown Select with PHP Mysqli</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.6.0/dist/jquery.min.js"></script> 
</head>
<body>
<?php
include('conn.php');
?>
 <div class="container mt-4">
 <h4 class="text-center">Jquery Ajax Dependent Dropdown Select with PHP Mysqli</h4><br>
   <div class="row">
    <div class="col-sm-4">
      <h6>Car Brand Name</h6>
        <select class="form-select" name="select" id="selectID">
        <option>Select Option</option>

        <?php $sql = "SELECT * FROM carbrands";
            $result = mysqli_query($conn,$sql);
            while($row = mysqli_fetch_assoc($result)) {?>
            <option value="<?php echo $row['brand_id'] ?>"><?php echo $row['brand_name'] ?></option>
            <?php }?>

        </select>
     </div> 

     <div class="col-sm-4">  
     <h6>Car Model</h6>
      <select  class="form-select"  name="select" id="show"></select>
    </div>
   
   </div>
 </div>  
<script>
  $(document).ready(function(){
     $('#selectID').change(function(){
      var Stdid = $('#selectID').val(); 

      $.ajax({
        type: 'POST',
        url: 'fetch.php',
        data: {id:Stdid},  
        success: function(data)  
         {
            $('#show').html(data);
         }
        });
     });
  });
</script> 
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
fetch.php
//fetch.php
<?php
  include('conn.php');

  $id = $_POST['id'];
  $sql = "SELECT * FROM carmodels WHERE brand_id= $id ";
  $result = mysqli_query($conn,$sql);

  $out='';
  while($row = mysqli_fetch_assoc($result)) 
  {   
     $out .=  '<option>'.$row['car_models'].'</option>'; 
  }
   echo $out;
?>

Load More Data using Jquery Ajax with PHP MySQLi

Load More Data using Jquery Ajax with PHP MySQLi


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.6.0/dist/jquery.min.js

CREATE TABLE `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `country` (`id`, `country`) VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia'),
(15, 'Austria'),
(16, 'Azerbaijan'),
(17, 'Bahamas'),
(18, 'Bahrain'),
(19, 'Bangladesh'),
(20, 'Barbados');

ALTER TABLE `country`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `country`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;


index.php
//index.php
<!DOCTYPE html>  
<html>  
<head>  
      <title>Load More Data using Jquery Ajax with PHP MySQLi</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.6.0/dist/jquery.min.js"></script>  
</head>  
<body>  
      <div class="container">   
        <div class="row">
              <h2 align="center">Load More Data using Jquery Ajax with PHP MySQLi</h2>
              <div id="loadtable">  
                  <?php
                    $lastid='';
                    include('conn.php');
                    $query=mysqli_query($conn,"select * from country order by id asc limit 5");
                    while($row=mysqli_fetch_array($query)){
                        ?>
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="btn btn-success" style="margin:10px;width:50%;"><?php echo $row['country']; ?></div>
                            </div>
                        </div>
                        <?php
                      $lastid=$row['id'];
                    }

                  ?>
                  <div id="remove">
                  <div class="row">
                      <div class="col-lg-12">
                      <button type="button" name="loadmore" id="loadmore" data-id="<?php echo $lastid; ?>" class="btn btn-primary">See More</button>
                      </div>
                  </div>
                  </div>  
                </div>  
          </div>  
      </div>

<script>
$(document).ready(function(){  
      $(document).on('click', '#loadmore', function(){  
           var lastid = $(this).data('id');  
           $('#loadmore').html('Loading...');  
           $.ajax({  
                url:"load_data.php",  
                method:"POST",  
                data:{
                    lastid:lastid,
                },  
                dataType:"text",  
                success:function(data)  
                {  
                     if(data != '')  
                     {  
                          $('#remove').remove();  
                          $('#loadtable').append(data);  
                     }  
                     else  
                     {  
                          $('#loadmore').html('No more data to show');  
                     }  
                }  
           });  
      });  
 }); 
</script>  
</body>  
</html>  
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
load_data.php
//load_data.php
<?php  
     sleep(1);  
     include('conn.php');
     if(isset($_POST['lastid'])){
          $lastid=$_POST['lastid'];
          $query=mysqli_query($conn,"select * from country where id > '$lastid' order by id asc limit 5");
  
          if(mysqli_num_rows($query) > 0){  
          while($row = mysqli_fetch_array($query)){  
               ?>
                    <div class="row">
                         <div class="col-lg-12">
                              <div class="btn btn-success" style="margin:10px;width:50%;"><?php echo $row['country']; ?></div>
                         </div>
                    </div>
               <?php
               $lastid=$row['id'];
          }
          ?>
          <div id="remove"> 
          <div id="remove_row" class="row">
               <div class="col-lg-12">
                    <button type="button" name="loadmore" id="loadmore" data-id="<?php echo $lastid; ?>" class="btn btn-primary">See More</button>
               </div>
          </div>
          </div> 
          <?php 
          }  
     }
?>

Monday, March 28, 2022

Submit Form using Jquey AJAX with PHP MySQLi

Submit Form using Jquey AJAX with PHP MySQLi

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.6.0/dist/jquery.min.js

Database Table

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>Submit Form using Jquey AJAX with PHP MySQLi</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
	<div class="card card-body bg-light">
		<div class="row">
			<div class="col-lg-12">
				<h2><center>Submit Form using Jquey AJAX with PHP MySQLi</center></h2>
			</div>
		</div>
		<form id="form">
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Firstname:</label>
				<input type="text" name="firstname" class="form-control">
			</div>
		</div>
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Lastname:</label>
				<input type="text" name="lastname" class="form-control">
			</div>
		</div>
		<div class="row">
			<div class="mb-3">
				<label class="form-label">Address:</label>
				<input type="text" name="address" class="form-control">
			</div>
		</div>
		</form>
		<div class="row">
			<div class="col-lg-12">
				<button type="button" class="btn btn-primary pull-right" id="submit">Submit</button>
			</div>
		</div>
	</div>
	<div class="row" style="margin-top:20px;">
		<div id="table">
		</div>
	</div>
</div>
<script>
$(document).ready(function(){

	showTable();

	$('#submit').click(function(){
		var form=$('#form').serialize();
		$.ajax({
			url:"add.php",
			method:"POST",
			data:form,
			success:function(){
				showTable();
				$('#form')[0].reset();
			} 
		});
	});
});

function showTable(){
	$.ajax({
		url:"fetch.php",
		method:"POST",
		data:{
			fetch: 1,
		},
		success:function(data){
			$('#table').html(data);
		}
	});
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","testingdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
 
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		?>
		<table class="table table-bordered table-striped">
			<thead>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Address</th>
			</thead>
			<tbody>
				<?php
					$query=mysqli_query($conn,"select * from members order by id desc");
					while($row=mysqli_fetch_array($query)){
					?>
					<tr>
						<td><?php echo $row['firstname']; ?></td>
						<td><?php echo $row['lastname']; ?></td>
						<td><?php echo $row['address']; ?></td>
					</tr>
					<?php
					}
				?>
			</tbody>
		</table>
		<?php	
	}
?>
add.php
//add.php
<?php 
	include('conn.php');
	if(isset($_POST['firstname'])){
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		$address=$_POST['address'];

		mysqli_query($conn,"insert into members (firstname, lastname, address) values ('$firstname', '$lastname', '$address')");
	}
?>

Thursday, March 10, 2022

PHP OOP Mysqli CRUD (Create Read Update and Delete) Jquery AJAX with Bootstrap 5 Modal

PHP OOP Mysqli CRUD (Create Read Update and Delete) Jquery AJAX with Bootstrap 5 Modal

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.6.0/dist/jquery.min.js

Bootstrap icons
https://icons.getbootstrap.com/#install
https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Caesar', 'Vance', 'New York');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP OOP Mysqli CRUD (Create Read Update and Delete) Jquery AJAX</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<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/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
</head>
<body>
	<body>
<div class="container">
	<div class="row"><p><h1>PHP OOP Mysqli CRUD (Create Read Update and Delete) Jquery AJAX with Bootstrap 5 Modal</h1></p></div>
	<div style="margin-left:auto; margin-right:auto; padding:auto; width:70%;">
		<p class="pull-right"><a id="add" style="cursor:pointer;" class="btn btn-primary"><i class="bi bi-clipboard2-plus-fill"></i> Add New</a></p>

		<div id="table"></div>
		<div id="alert" class="alert alert-success" style="display:none;">
			<center><span id="alerttext"></span></center>
		</div>
	</div>
<?php include('modal.php'); ?>
</div>
<script>
$(document).ready(function(){
	showTable();

	//add
	$('#add').click(function(){
		$('#addnew').modal('show');
		$('#addForm')[0].reset();
	});

	$('#addbutton').click(function(){
		var first = $('#firstname').val();
		var last = $('#lastname').val();
		var address = $('#address').val();
		if(first!='' && last!==''){
			var addForm = $('#addForm').serialize();
			$.ajax({
				type: 'POST',
				url: 'add.php',
				data: addForm,
				success:function(){
					$('#addnew').modal('hide');
					$('#addForm')[0].reset();
					showTable();
					$('#alert').slideDown();
					$('#alerttext').text('Member Added Successfully');
				}
			});
		}
		else{
			alert('Please input both Fields')
		}
		
	});
	//
	//edit
	$(document).on('click', '.edit', function(){
		var id = $(this).data('id'); 
		var first = $('#first'+id).text();
		var last = $('#last'+id).text(); 
		var address = $('#address'+id).text(); 
		$('#editmem').modal('show');
		$('#eid').val(id);
		$('#efirstname').val(first);
		$('#elastname').val(last);
		$('#eaddress').val(address);
	});

	$('#editbutton').click(function(){
		var id = $('#eid').val(); //alert(id);
		var editForm = $('#editForm').serialize();
		$.ajax({
			type: 'POST',
			url: 'edit.php',
			data: editForm + "&id="+id,
			success:function(response){
				console.log(response);
				$('#editmem').modal('hide');
				$('#editForm')[0].reset();
				showTable();
				$('#alert').slideDown();
				$('#alerttext').text('Member Updated Successfully');
			}
		});
	});
	//
	//delete
	$(document).on('click', '.delete', function(){
		var id = $(this).data('id');
		var first = $('#first'+id).text();
		$('#delmem').modal('show');
		$('#dfirstname').text(first);
		$('#delbutton').val(id);
	});

	$('#delbutton').click(function(){
		var id = $(this).val();
		$.ajax({
			type: 'POST',
			url: 'delete.php',
			data: {
				id: id,
			},
			success:function(){
				$('#delmem').modal('hide');
				showTable();
				$('#alert').slideDown();
				$('#alerttext').text('Member Deleted Successfully');
			}
		});
	});

});

function showTable(){
	$.ajax({
		type: 'POST',
		url: 'fetch.php',
		data: {
			fetch: 1
		},
		success:function(data){
			$('#table').html(data);
		}
	});
}
</script>
</body>
</html>
conn.php
//conn.php
<?php
$conn = new mysqli("localhost", "root", "", "testingdb");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
fetch.php
//fetch.php
<?php
	include('conn.php');
	if(isset($_POST['fetch'])){
		?>
		<table class="table table-striped table-bordered table-hover">
			<thead>
				<th>Firstname</th>
				<th>Lastname</th>
				<th>Address</th>
				<th>Action</th>
			</thead>
			<tbody>
			<?php
				$query=$conn->query("select * from members");
				while($row=$query->fetch_array()){
					?>
					<tr>
						<td><span id="first<?php echo $row['id']; ?>"><?php echo $row['firstname']; ?></span></td>
						<td><span id="last<?php echo $row['id']; ?>"><?php echo $row['lastname']; ?></span></td>
						<td><span id="address<?php echo $row['id']; ?>"><?php echo $row['address']; ?></span></td>
						<td>
							<a style="cursor:pointer;" class="btn btn-warning edit" data-id="<?php echo $row['id']; ?>"><i class="bi bi-pencil"></i> Edit</a> || 
							<a style="cursor:pointer;" class="btn btn-danger delete" data-id="<?php echo $row['id']; ?>"><i class="bi bi-trash"></i> Delete</a>
						</td>
					</tr>
					<?php
				}
			
			?>
			</tbody>
		</table>
		<?php
	}
?>
add.php
//add.php
<?php
	include('conn.php');
	if(isset($_POST['firstname'])){
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		$address=$_POST['address'];

		$conn->query("insert into members (firstname, lastname, address) values ('$firstname', '$lastname', '$address')");
	}
?>
modal.php
//modal.php
<!-- Add New -->
    <div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
			      <div class="modal-header">
					<h5 class="modal-title" id="exampleModalLabel">Add New Member</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				  </div>
                <div class="modal-body">
				<div class="container-fluid">
				<form id="addForm">
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="firstname" id="firstname">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="lastname" id="lastname">
						</div>
					</div>				
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Address:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="address" id="address">
						</div>
					</div>
                </div> 
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" id="addbutton" class="btn btn-primary"> Save</a>
				</form>
                </div>
				
            </div>
        </div>
    </div>

<!-- Edit -->
	<div class="modal fade" id="editmem" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="exampleModalLabel">Edit Member</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
                <div class="modal-body">
				<div class="container-fluid">
				<form id="editForm">
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Firstname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="efirstname" id="efirstname">
						</div>
					</div>
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2"><input type="hidden" name="eid" id="eid">
							<label class="control-label" style="position:relative; top:7px;">Lastname:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="elastname" id="elastname">
						</div>
					</div>					
					<div style="height:10px;"></div>
					<div class="row">
						<div class="col-md-2">
							<label class="control-label" style="position:relative; top:7px;">Address:</label>
						</div>
						<div class="col-md-10">
							<input type="text" class="form-control" name="eaddress" id="eaddress">
						</div>
					</div>
                </div> 
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" id="editbutton" class="btn btn-warning"> Update</a>
				</form>
                </div>
				
            </div>
        </div>
    </div>

<!-- Delete -->
    <div class="modal fade" id="delmem" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="exampleModalLabel">Delete Member</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
                <div class="modal-body">
				<div class="container-fluid">
					<h5><center>Firstname: <strong><span id="dfirstname"></span></strong></center></h5> 
                </div> 
				</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" id="delbutton" class="btn btn-danger"> Delete</button>
                </div>
				
            </div>
        </div>
    </div>
edit.php
//edit.php
<?php
	include('conn.php');
	if(isset($_POST['efirstname'])){
		$firstname=$_POST['efirstname'];
		$lastname=$_POST['elastname'];
		$address=$_POST['eaddress'];
		$id=$_POST['id'];

		$conn->query("update members set firstname='$firstname', lastname='$lastname', address='$address' where id='$id'");

		$response[] = array("firstname"=>$firstname,"lastname" => $lastname,"address" => $address,"member_id" => $id);
		echo json_encode($response);
	}
?>
delete.php
//delete.php
<?php
	include('conn.php');
	if(isset($_POST['id'])){
		$id=$_POST['id'];

		$conn->query("delete from members where id='$id'");
	}
?>

Related Post