Krati Pillai Krati Pillai - 7 months ago 19
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");
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");?>

Answer

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>