-2

我似乎在下面的代码中遇到了问题。出现的问题是

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

“警告: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>

有谁知道如何修理它?

4

2 回答 2

0

You are just incrementing the variable which is not assigned yet

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

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

or else simply do

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

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

i think this will be the reason for warning mysql_num_rows() too

于 2012-12-22T09:52:27.933 回答
0

错误1: 使用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);
}
于 2012-12-22T09:56:55.150 回答