Blog » PHP » php mysql search box

php mysql search box

In this article will show you how to create a simple search box using PHP. this a simple programming to learn.this script will display the user entered search products. if was not there search products,in database. script will display no search results found message. I hope this simple script you will usefulness. what you are looking for.

First of all you have to create a database name on your server. I have added a database name of it name search.


Creating database connection


here is the database connection.


<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "search";
$con = new mysqli($servername, $username, $password, $database);
if($con->connect_error){
die("connection failed<br/>");
}
?>


This is the PHP script.


<?php
if(isset($_POST['search'])){
$search = $_POST['search'];
$sql = "SELECT * FROM products where title like '%$search%'";
}else{
$sql = "SELECT * FROM products ORDER BY id DESC";
}
$result = $con->query($sql); 
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<tr><td><img src='images/<?php echo $row['img'];?>'></td>
<td><?php echo $row['title'];?></td></tr>
<?php
}
}else{
echo"no search results found";
}
?>


Completed source code


<!DOCTYPE HTML>
<html lang="">
<head>
<meta charset="UTF-8">
<title>Search</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="styles/style.css" rel="stylesheet" type="text/css" />
<div class="search">
<form action="" method="post" name="search" id="search" style="display:inline;">
<input id="search-box" name="search" size="40" type="text" placeholder="Search............"/>
<input id="search-btn" value="Search" type="submit"/>
</form>
</div>
<table width="" height="" id="table-s">
<tr><th scope="col">Image</th><th scope="col">Title</th></tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "search";
$con = new mysqli($servername, $username, $password, $database);
if($con->connect_error){
die("connection failed<br/>");
}
if(isset($_POST['search'])){
$search = $_POST['search'];
$sql = "SELECT * FROM products where title like '%$search%'";
}else{
$sql = "SELECT * FROM products ORDER BY id DESC";
}
$result = $con->query($sql); 
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<tr><td><img src='images/<?php echo $row['img'];?>'></td>
<td><?php echo $row['title'];?></td></tr>
<?php
}
}else{
echo"no search results found";
}
?>
</table>
</body>
</html>
ARTICLE POSTED BY : Admin

Hi, I'am k.g uththara. I'm a professional web developer. I write blog posts in my free time. if you want to contact me, send a message on contact page, thanks.