如何使用php搜索栏检索MySQL数据库数据

时间:2014-10-31 09:25:58

标签: php mysql

我使用PHP创建了一个搜索栏,我想检索MySQL数据库中的数据。

我的代码如下:

<?php

$button = $_GET ['submit'];
$search = $_GET ['search'];

if(!$button)
echo "You searched for '<b>$search</b>' <hr size='1'</br>";
$con=mysqli_connect("localhost", "root", "root", "PM_DB");

if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$search_exploded = explode (" ", $search);

foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="keywords LIKE '%$search_each%'";
else
$construct .="AND keywords LIKE '%$search_each%'";

}

$construct ="SELECT * FROM Leads WHERE $construct";
$run = mysqli_query($construct);

$foundnum = mysqli_num_rows($run);

if ($foundnum==0)
echo "There are no results for <b>'$search'</b>. Please check your spelling.";
else
{
echo "$foundnum results found !<p>";

while($runrows = mysqli_fetch_assoc($run))
{
$Company = $runrows['Clients'];

echo "<a href='$Company'><b>Company</b></a><br>";

}
}

?>

每次点击搜索时,它都会返回错误消息。我错过了什么?任何建议将受到高度赞赏!谢谢 - Tijger。

2 个答案:

答案 0 :(得分:0)

试试此代码

$search_exploded = explode(" ", $search);

$construct = "SELECT * FROM Leads WHERE keywords LIKE ";
$construct .= "'%".implode("%' OR '%", $search_exploded)."%'";

$run = mysqli_query($construct);

Live demo

答案 1 :(得分:0)

我要求OP的代码

我评论了导致他出错的两行

他正在执行正确的查询,然后再次执行错误的查询...这就是为什么没有返回结果。

<?php
        $button = $_GET ['submit'];
        $search = $_GET ['search'];

        if (!$button)
            echo "You searched for '<b>$Search</b>' <hr size='1'</br>";
        $con = mysqli_connect("localhost", "root", "root", "PM_DB");

        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        $search_exploded = explode(" ", $search);

        $construct = "SELECT * FROM Leads WHERE keywords LIKE ";
        $construct .= "'%" . implode("%' OR '%", $search_exploded) . "%'";

        $run = mysqli_query($construct) or die(mysql_error());

        // Why thisssssssssssssssssss??????????? OMG
        //$construct = "SELECT * FROM Leads WHERE $construct";
        //$run = mysqli_query($construct);

        $foundnum = mysqli_num_rows($run) or die(mysql_error());

        if ($foundnum == 0)
            echo "There are no results for <b>'$search'</b>. Please check your spelling.";
        else {
            echo "$foundnum results found !<p>";

            while ($runrows = mysqli_fetch_assoc($run)) {
                $Company = $runrows['Clients'];

                echo "<a href='$Company'><b>Company</b></a><br>";
            }
        }
        ?>