Search bar with PHP & MYSQL
<?php
/**
* Database Credentials
*/
$mysql_username = "root";
$mysql_password = "root";
$mysql_database = "demo";
$mysql_host = "127.0.0.1";
$output = '';
/**
* Databse Connection
*/
$mysql_connection = mysqli_connect($mysql_host, $mysql_username, $mysql_password, $mysql_database);
/**
* Check connection
*/
if ($mysql_connection === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
/**
* Search Logic
*/
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$query = mysqli_query($mysql_connection, "SELECT name FROM users WHERE name LIKE '%$searchq%'");
$count = mysqli_num_rows($query);
if ($count == 0) {
$output = 'There are no such results';
} else {
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$name = $row['name'];
$output .= '<div>' . $name . '<div>';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Search</title>
</head>
<body>
<form method="post" action="index.php">
<input type="text" name="search" id="search" placeholder="Search users...">
<input type="submit" value="Search">
</form>
<!-- Output of Search-->
<?= $output ?>
</body>
</html>