搜索不使用PHP工作

时间:2016-04-18 10:14:46

标签: php mysql mysqli

这是我的搜索代码,当我点击搜索按钮时,它会提供所有值的输出,而不是搜索特定的产品标题。

任何帮助??

<?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");?>

1 个答案:

答案 0 :(得分:1)

您在

处缺少连接变量
mysqli_select_db("onlinegrocery");

它需要第一个参数作为您的数据库连接

这将是

mysqli_select_db($con,"onlinegrocery");

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

您的代码是开放的,用于古老的SQL注入检查How can I prevent SQL injection in PHP?以防止它

忘记搜索表单中的名称属性

<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>