搜索引擎错误

时间:2012-12-22 09:34:00

标签: php search-engine

我接下来要解决下面代码中的问题。出现的问题是

  

“注意:未定义的变量:我在C:\ wamp \ www \ search \ search.php上   第21行“

  

“警告:mysql_num_rows()期望参数1是资源,布尔值   在第34行的C:\ wamp \ www \ search \ search.php中给出。“

第21行是$i++;

第34行是$num_rows = mysql_num_rows($query)

<body>
    <h2>Search Engine</h2>
    <form action='./search.php' method='get'>
        <input type='text' name='k' size='50' value='<?php echo $_GET['k'] ?>' />
        <input type='submit' value='Search'/>
    </form>
    <hr />
    <?php
    $k = $_GET['k'];
    $terms = explode(" ", $k);
    $query = "SELECT * FROM search WHERE ";

    foreach ($terms as $each){
        $i++;

        if($i == 1)
            $query .= "keywords LIKE '%$each%' ";
        else
            $query .= "OR keywords LIKE '%$each%' ";
    }

    //connect
    mysql_connect("localhost", "root", "password");
    mysql_select_db("search");

    $query = mysql_query($query);
    $num_rows = mysql_num_rows($query);

    if ($num_rows > 0){

        while($row = mysql_fetch_assoc($query)){
            $id = $row['id'];
            $title = $row['title'];
            $description = $row['description'];
            $keywords = $row['Keywords'];
            $link = $row['link'];

            echo "<h2><a href='$link'>$title</a></h2>
            $description<br /><br />";
        }

    }
    else
        echo "No results found for \"<b>$k</b>\"";

    //disconnect
    mysql_close();

    ?>
</body>

有谁知道如何修复它?

2 个答案:

答案 0 :(得分:0)

您只是递增尚未分配的变量

$i = 1;
foreach ($terms as $each){
        $i++;

        if($i == 1)
            $query .= "keywords LIKE '%$each%' ";
        else
            $query .= "OR keywords LIKE '%$each%' ";
    }

或者只是做

foreach ($terms as $each){
        $selects[] = "keywords LIKE '%$each%' ";

}
$query .= implode(" OR ",$selects);

我认为这也是警告mysql_num_rows()

的原因

答案 1 :(得分:0)

<强> ERROR1: 使用for循环:

foreach ($terms as $each)
{
    //....
}

for($i = 0; i < count($terms); i++)
{
    $each = $terms[i];
    //....
}

$ i ++在foreach

中没用

<强>误差2: 如果用户没有访问查询引用的表的权限,mysql_query()将失败并返回FALSE。 所以这里有一个示例代码来修复它:

$num_rows = 0;
if($query){
    $num_rows = mysql_num_rows($query);
}