Basic PHP Search Bar
Basic PHP Search Bar
Watch the full tutorial here:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="./server.php" method="get">
<input type="search" name="product">
<button type="submit">search</button>
</form>
</body>
</html>
php
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=product_db", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection faild: ' . $e->getMessage();
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['product'])) {
$search = $_GET['product'];
$query = "SELECT * FROM product_tbl WHERE CONCAT(p_name, ' ', p_desc)
LIKE CONCAT('%', :search, '%')
OR p_name LIKE CONCAT('%', :search, '%')
OR p_desc LIKE CONCAT('%', :search, '%')
ORDER BY id desc";
$stmt = $pdo->prepare($query);
$stmt->bindValue(":search", $search);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
if ($results) {
foreach ($results as $data) {
echo "
<ul>
<li>product name: $data->p_name</li>
<li>product description: $data->p_desc</li>
<li>product price: $data->p_price</li>
</ul>
";
}
} else {
echo 'No Products Found';
}
}
sql
-- Product search demo database structure and sample data
-- Create table
CREATE TABLE `product_tbl` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`p_name` VARCHAR(250) DEFAULT NULL,
`p_desc` VARCHAR(250) DEFAULT NULL,
`p_price` DECIMAL(10,2) DEFAULT NULL,
`create_at` DATE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Insert sample products
INSERT INTO `product_tbl` (`p_name`, `p_desc`, `p_price`, `create_at`) VALUES
('Nike Air Max Dn8', 'More Air, less bulk. The Dn8 takes our Dynamic Air system and condenses it into a sleek, low-profile package.', 190.00, '2025-05-10'),
('adidas Samba OG Shoes', 'Timeless street style with modern comfort, making them a versatile addition to any wardrobe.', 47.97, '2025-05-10'),
('adidas Originals SL 72', 'Women\'s SL 72 for running and walking.', 79.99, '2025-05-10'),
('New Balance 9060', 'Women\'s 9060 in yellow color.', 99.99, '2025-05-10'),
('Nike T-Shirt', 'Fresh As It Gets Graphic T-Shirt.', 19.99, '2025-05-10');