article

Tuesday, August 2, 2022

PHP Mysql PDO AutoComplete Search with Jquery Ajax

PHP Mysql PDO AutoComplete Search with Jquery Ajax

CREATE TABLE `countries` (
  `id` int(6) NOT NULL,
  `name` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>PHP Mysql PDO AutoComplete Search with Jquery Ajax</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body class="bg-warning">
  <div class="container">
    <div class="row mt-4">
      <div class="col-md-8 mx-auto bg-light rounded p-4">
        <h5 class="text-center font-weight-bold">PHP Mysql PDO AutoComplete Search with Jquery Ajax</h5>
        <hr class="my-1">
		<form action="details.php" method="post">
		<div class="input-group mb-3">
		  <input type="text" class="form-control" name="search" id="search" placeholder="Search..." aria-describedby="basic-addon2" autocomplete="off">
		  <button class="btn btn-outline-secondary" type="submit" name="submit" id="basic-addon22">Search</button>
		</div>
		</form>
		<div class="card list-group" id="show-list"></div>
      </div>
    </div>
  </div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
$(document).ready(function () {
  // Send Search Text to the server
  $("#search").keyup(function () {
    let searchText = $(this).val();
    if (searchText != "") {
      $.ajax({
        url: "action.php",
        method: "post",
        data: {
          query: searchText,
        },
        success: function (response) {
          $("#show-list").html(response);
        },
      });
    } else {
      $("#show-list").html("");
    }
  });
  // Set searched text in input field on click of search button
  $(document).on("click", "a", function () {
    $("#search").val($(this).text());
    $("#show-list").html("");
  });
});
</script>
</body>
</html>
config.php
//config.php
<?php
  const DBHOST = 'localhost';       
  const DBUSER = 'root';             
  const DBPASS = '';                
  const DBNAME = 'projectdb';  

  // Data Source Network
  $dsn = 'mysql:host=' . DBHOST . ';dbname=' . DBNAME . '';

  // Connection Variable
  $conn = null;

  // Connect Using PDO (PHP Data Output)
  try {
    $conn = new PDO($dsn, DBUSER, DBPASS);
    $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  } catch (PDOException $e) {
    die('Error : ' . $e->getMessage());
  }
?>
action.php
//action.php
<?php
  require_once 'config.php';

  if (isset($_POST['query'])) {
    $inpText = $_POST['query'];
    $sql = 'SELECT name FROM countries WHERE name LIKE :country';
    $stmt = $conn->prepare($sql);
    $stmt->execute(['country' => '%' . $inpText . '%']);
    $result = $stmt->fetchAll();

    if ($result) {
      foreach ($result as $row) {
        echo '<a href="#" class="list-group-item list-group-item-action border-1">' . $row['name'] . '</a>';
      }
    } else {
      echo '<p class="list-group-item border-1">No Record</p>';
    }
  }
?>
details.php
//details.php
<?php
  require_once 'config.php';

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

    $sql = 'SELECT * FROM countries WHERE name = :name';
    $stmt = $conn->prepare($sql);
    $stmt->execute(['name' => $countryName]);
    $row = $stmt->fetch();
  } else {
    header('location: .');
    exit();
  }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Details</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 class="row mt-5">
      <div class="col-5 mx-auto">
        <div class="card shadow text-center">
          <div class="card-header">
            <h1><?php echo $row['name']; ?></h1>
          </div>
          <div class="card-body">
            <h4><b>Country Code :</b> <?php echo $row['name']; ?></h4>
            <h4><b>Country ID :</b> <?php echo $row['id']; ?></h4>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

Related Post