将多个类似的语句分组

时间:2014-05-29 16:12:53

标签: php mysql

我是SQL的新手似乎无法将多个LIKE语句组合在一起。知道我做错了吗?

$query = mysqli_query($mysqli, "SELECT * FROM table_name
            WHERE Page LIKE ".$page."
            AND Profession LIKE ".$profession.", 
            AND Age LIKE ".$age."");

感谢。

2 个答案:

答案 0 :(得分:1)

可能是因为它们未正确封闭

$query = mysqli_query($mysqli, "SELECT * FROM table_name
            WHERE Page LIKE ".$page."
            AND Profession LIKE ".$profession."
            AND Age LIKE ".$age."");

编译时类似

SELECT * FROM table_name
            WHERE Page LIKE page number 1
            AND Profession LIKE my profession
            AND Age LIKE 100

这是无效的SQL

您需要使用引号并转义值

$query = mysqli_query($mysqli, "SELECT * FROM table_name
            WHERE Page LIKE '%".$page."%'
            AND Profession LIKE '%".$profession."%'
            AND Age LIKE '%".$age."%'");

会给出

SELECT * FROM table_name
            WHERE Page LIKE '%page number 1%'
            AND Profession LIKE '%my profession%'
            AND Age LIKE '%100%'

这可能会产生您期望的结果

使用http://www.php.net/manual/en/mysqli.real-escape-string.php确保值是安全的,尽管查看准备好的语句是更好的选择

修改

LIKE ". $profession."

之后删除逗号

答案 1 :(得分:0)

如果使用占位符和bind_param

,这将更容易实现
$stmt = mysqli_query($mysqli, "SELECT * FROM table_name
            WHERE Page LIKE ?
            AND Profession LIKE ?
            AND Age=?");

mysqli_stmt_bind_param($stmt, 'ssi', "%" . $page . "%", "%" . $profession. "%", $age);

mysqli_stmt_execute($stmt);