MySQL搜索没有返回LIKE'complete_string'的结果

时间:2015-07-27 16:46:03

标签: php mysql

我有一个化学数据库,用户可以搜索物品。如果我搜索测试项目,例如“海洛因”(在我的数据库中作为测试行存在),则不会返回任何结果,但是如果搜索是“她”,则会生成相应的结果。

当我在数据库(Navicat mysql)中运行SQL脚本时,我得到了正确的结果,所以我认为问题出在我的PHP代码上。 (是的,我知道我应该升级到PDO结构,但这并不能解决当前的问题。)

我的PHP脚本有一个返回$item的搜索字段。

$item只是部分匹配时,我得到了预期的结果,但是,当$item与整个字符串相同时,没有返回匹配。

$item = $_POST['item'];
$log_data = 'Searched for ' . $item;
$user_name = $user_data['username'];
user_log($user_name, $log_data);
$item=trim($item);
if($item !== ""){
    $count = 0;
    $chem = mysql_query("SELECT *
        FROM Chemicals
        WHERE Chemicals.Name_Chem1 LIKE '%{$item}%'
        ORDER BY Chemicals.Name_Chem1 ASC");
    while ($row = mysql_fetch_array($chem)) {
        echo "<table border='0'>
            <tr class='content'>
                <th>CAS</th>
                <th>Name</th>
                <th>IUPAC Name</th>
                <th>Common Name</th>
                <th>German Chemical</th>
                <th>German Common</th>
            </tr>";
        while ($row = mysql_fetch_array($chem)) {
            $count ++;
            echo "<tr>";
            echo "<td class='content'>" . $row['CAS'] . "</td>";
            echo "<td class='content'>" . "<a href='item_result.php?CAS="
                . $row['CAS'] . "'>" . $row['Name_Chem1'] . "</a>" . "</td>";
            echo "<td class='content'>" . $row['Name_IUPAC'] . "</td>";
            echo "<td class='content'>" . $row['Name_Common'] . "</td>";
            echo "<td class='content'>" . $row['Name_German_Chemical'] . "</td>";
            echo "<td class='content'>" . $row['Name_German_Common'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    echo  "There are ", $count, "results.";
}

查询在MySQL中运行良好,但在PHP脚本中没有。

1 个答案:

答案 0 :(得分:0)

这是问题所在。您的获取代码的结构如下:

while ($row = mysql_fetch_array($chem)) {
    while ($row = mysql_fetch_array($chem)) {
        // Do something
    }
}

每次调用fetch函数时,它“消耗”一行并将内部结果指针移动一。因此,当您搜索您期望的结果时,在运行内部循环时,您已经在外部循环中使用了该行。

外部循环应替换为if(),而不是检查结果计数。