STEP 1) HTML SEARCH FORM
form.php
<!DOCTYPE html>
<html>
<body>
<!-- [SEARCH FORM] -->
<form method="post" action="1-form.php">
<h1>SEARCH FOR USERS</h1>
<input type="text" name="search" required/>
<input type="submit" value="Search"/>
</form>
<?php
if (isset($_POST['search'])) {
// SEARCH FOR USERS
require "2-search.php";
// DISPLAY RESULTS
if (count($results) > 0) {
foreach ($results as $r) {
printf("<div>%s - %s</div>", $r['name'], $r['email']);
}
} else {
echo "No results found";
}
}
?>
</body>
</html>
STEP 2) THE SEARCH SCRIPT
<?php
// (1) DATABASE CONFIG
// ! CHANGE THESE TO YOUR OWN !
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
// (2) CONNECT TO DATABASE
try {
$pdo = new PDO(
"mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET . ";dbname=" . DB_NAME,
DB_USER, DB_PASSWORD, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false ]
);
} catch (Exception $ex) {
die($ex->getMessage());
}
// (3) SEARCH
$stmt = $pdo->prepare("SELECT * FROM `users` WHERE `name` LIKE ? OR `email` LIKE ?");
$stmt->execute(["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]);
$results = $stmt->fetchAll();
if (isset($_POST['ajax'])) { echo json_encode($results); }