Create Search.php file
<?php
$host = 'localhost';
$user = 'root'; // or your DB user
$pass = 'evrig'; // your DB password
$db = 'corephp'; // replace with your DB name
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!empty($_POST['keyword'])) {
$keyword = $_POST['keyword'];
$keyword = "%{$keyword}%";
$stmt = $conn->prepare("SELECT id, name FROM search_data WHERE name LIKE ? LIMIT 20");
$stmt->bind_param("s", $keyword);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . htmlspecialchars($row['id']) . "</td><td>" . htmlspecialchars($row['name']) . "</td></tr>";
}
} else {
echo "<tr><td colspan='2'>No results found</td></tr>";
}
$stmt->close();
}
$conn->close();
?>
___________________
Create Form.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Search</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="p-4">
<div class="container">
<h2 class="mb-3">Live Search</h2>
<input type="text" id="search" class="form-control" placeholder="Type to search..." autocomplete="off">
<div class="mt-3">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody id="result">
<!-- Results will be populated here -->
</tbody>
</table>
</div>
</div>
<script>
$(document).ready(function () {
$('#search').on('input', function () {
const query = $(this).val();
if (query.length >= 3) {
$.ajax({
url: 'search.php',
type: 'POST',
data: { keyword: query },
success: function (data) {
$('#result').html(data);
}
});
} else {
$('#result').html('');
}
});
});
</script>
</body>
</html>
Comments
Post a Comment