Krati Pillai Krati Pillai - 2 years ago 80
SQL Question

Search not working using php

This is my search code, when i click the search button, it gives output of all the values instead of searching the particular product title.

Any Help??

<?php include("config.php");
$output = "";

if(isset($_POST['search'])) {

$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

$query = "SELECT * FROM tbl_product WHERE product_title LIKE '%$searchq%'";
$count = mysqli_num_rows($sql);
if($count == 0) {
$output = 'Nothing Found';
else {
while($row = mysqli_fetch_array($sql)){
$product_title = $row['product_title'];
$id = $row['product_id'];

$output .= '<div> '.$product_title.' </div>';


<form action="index.php" method="post">
<input type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button class="btn btn-default" type="submit" name="search"><i class="glyphicon glyphicon-search"></i></button>
<?php echo("$output");?>

Answer Source

You are missing connection variable at


It need first parameter as your database connection

It would be



Your code is open for venerable sql injection check How can I prevent SQL-injection in PHP? to prevent it

Forget name attribute in search form it would be

<form action="index.php" method="post">
    <input type="text" class="form-control" placeholder="Search" name="search">
    <div class="input-group-btn">
        <button class="btn btn-default" type="submit" name="submit"><i class="glyphicon glyphicon-search"></i></button>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download