article

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;
 ?>

Related Post