0

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");
mysqli_select_db("onlinegrocery");
$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%'";
$sql=mysqli_query($con,$query);
$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>
                                </div>
                            </form>
                        <?php echo("$output");?>
Saty
  • 22,443
  • 7
  • 33
  • 51
Peace
  • 616
  • 2
  • 8
  • 24
  • i think `"#[^0-9a-z]#i"` you should not remove whitespaces from search query. `"#[^0-9a-z\s]#i"` – jekaby Apr 18 '16 at 10:21

1 Answers1

1

You are missing connection variable at

mysqli_select_db("onlinegrocery");

It need first parameter as your database connection

It would be

mysqli_select_db($con,"onlinegrocery");

read http://php.net/manual/en/mysqli.select-db.php

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>
    </div>
</form>
Community
  • 1
  • 1
Saty
  • 22,443
  • 7
  • 33
  • 51