我正在用PHP(带有PDO)和MySQL创建一个简单的搜索引擎,其目标是在库存中查找产品。
我的TABLE phone
有一个COLUMN snowden
,它是TINYINT
(包含0
或1
)。如果phone.snowden
是true
并且用户的输入是'snowden'
,我希望能够得到结果。
这是我的查询的简短版本:(:search_0
是用户的输入。这是针对PDO的准备好的查询)
SELECT * FROM phone WHERE phone.snowden = 1 AND :search_0 = `snowden`
当然,实际查询实际上更长(连接多个表并搜索许多列),但是除此以外,其他所有方法都有效。
当我尝试搜索
'snowden'
时,没有任何结果(表示未在任何列中找到关键字,并且'snowden'的情况不起作用)。我会错过有关语法的内容吗?
如何以尝试的方式实现此查询?
如何通过与列名进行比较来实现此目的(如果这是更好的处理方式)?
编辑:完整代码
这是我使用的完整代码:
$keywords = explode(" ", $_POST['query']);
$query = "SELECT phone.id, phone.imei, phone.model, phone.color, phone.capacity, phone.grade, phone.sourcing, phone.entry, phone.canal, phone.sale, phone.state, phone.snowden FROM phone LEFT JOIN capacity ON (phone.capacity = capacity.id) LEFT JOIN color ON (capacity.color = color.id) LEFT JOIN model ON (color.model = model.id) LEFT JOIN grade ON (phone.grade = grade.id) WHERE ";
$query_array = array();
for ($i = 0; $i < count($keywords); $i += 1) {
$query .= " ( phone.imei LIKE :search_" . $i;
$query .= " OR phone.sourcing LIKE :search_" . $i;
$query .= " OR phone.canal LIKE :search_" . $i;
$query .= " OR phone.entry LIKE :search_" . $i;
$query .= " OR phone.sale LIKE :search_" . $i;
$query .= " OR phone.state LIKE :search_" . $i;
$query .= " OR ( phone.snowden = 1 AND ':search_" . $i . "' = `snowden` )";
$query .= " OR model.name LIKE :search_" . $i;
$query .= " OR color.name LIKE :search_" . $i;
$query .= " OR capacity.amount LIKE :search_" . $i;
$query .= " OR grade.name LIKE :search_" . $i;
if ($i != (count($keywords) - 1)) {
$query .= " ) AND ";
} else {
$query .= " ) ";
}
if (strtolower($keywords[$i]) == 'snowden') {
$query_array['search_' . $i] = $keywords[$i];
} else {
$query_array['search_' . $i] = "%" . $keywords[$i] . "%";
}
}
$query .= "ORDER BY phone.id DESC";
$results = $stock->prepare($query);
$results->execute($query_array);
最佳答案
替换你的线
$query .= " OR ( phone.snowden = 1 AND ':search_" . $i . "' = `snowden` )";
与
$query .= " OR ( phone.snowden = 1 AND 'snowden'= :search_" . $i )";