使用PHP的通配符的MySQL语句不起作用

时间:2013-11-08 13:42:32

标签: php mysql

解决:不知道为什么,但在重新加载LAMP堆栈后,一切都开始正常工作了。谢谢大家的帮助!

我在PHP中编写了以下MySQL语句:

SELECT * FROM my_table WHERE (country LIKE 'Latvia' AND phone NOT LIKE '371%')

选择包含错误国家/地区电话代码的记录。 在php中它看起来像这样:

$sql = "SELECT * FROM {$table_name} WHERE (
    country LIKE '$country' AND phone NOT LIKE '$phone_code%')";

虽然它完美地过滤了phpMyAdmin中的记录,但它在我的应用程序中不起作用 - 我得到的所有记录包括正确的记录。非常感谢您的帮助!

编辑: 以下是更多代码的样子:

    while ($row = $this->fetch_array($result_set)) {
        $countries_to_check[$row['short_name']] = $row['calling_code'];
    }
    $i = 1;
    $sql = "SELECT * FROM {$this->table_name} WHERE ";
    foreach ($countries_to_check as $country => $phone_code) {
        if ($i > 1) {
            $sql .= " OR ";
        }
        $sql .= "(country LIKE '".$country."' AND phone NOT LIKE '".$phone_code."%')";
        $i++;
    }
    $result_set = $this->query($sql);

正如我在评论中写的那样,所有的变量都不是空的,我已经回复了$ sql,甚至在phpMyAdmin中运行了这个查询,并且成功了。

结果如下所示:

country     phone   
Lithuania           37028694529 * Correct
Latvia      37122171755 * Correct
Latvia      37522433153     * Incorrect
Latvia      +37126378238    * Incorrect

2 个答案:

答案 0 :(得分:0)

curly syntax

$sql = "SELECT * FROM {$table_name} WHERE (
    country LIKE '{$country}' AND phone NOT LIKE '{$phone_code}%')";

答案 1 :(得分:-4)

一定是这样:

$sql = "SELECT * FROM {$table_name} WHERE (
country LIKE '".$country."' AND phone NOT LIKE '".$phone_code."%')";