我有一个php搜索表单,包含两个字段。一个用于$code
,另一个用于"$name"。用户使用其中一个,而不是同时使用。提交通过$_POST
发送。在接收php文件中,我有:
SELECT * FROM list WHERE code = '$code' OR name = '$name' ORDER BY code"
一切都很好,但我希望$code是一个精确的搜索,而$name是野生的。当我尝试时:
SELECT * FROM list WHERE code = '$code' OR name = '%$name%' ORDER BY code
只有$code
有效,而$name不提供任何内容。我尝试了多种方法。将=
更改为LIKE
,放入括号等。但只有一种方法或其他方法有效。
有什么办法我能做到这一点吗?还是我必须采取另一种方法?
感谢
如果只想接受一个或另一个,那么只添加要测试的一个。
此外,在MySQL中进行通配符搜索时,使用LIKE
而不是=
。如果值为空,我们也不想添加该条件,因为它将变成LIKE '%%'
,这将匹配所有内容。
您还应该使用参数化的准备语句,而不是将数据直接注入到查询中。
我在示例中使用了PDO,因为它是最容易使用的数据库API,而您没有提到您使用的是哪一个。同样的事情也可以在mysqli上做一些调整。
我使用$pdo
,就好像它包含以下代码中的PDO实例(数据库连接(:
// This will contain the where condition to use
$condition = '';
// This is where we add the values we're matching against
// (this is specifically so we can use prepared statements)
$params = [];
if (!empty($_POST['code'])) {
// We have a value, let's match with code then
$condition = "code = ?";
$params[] = $_POST['code'];
} else if (!empty($_POST['name'])){
// We have a value, let's match with name then
$condition = "name LIKE ?";
// We need to add the wild cards to the value
$params[] = '%' . $_POST['name'] . '%';
}
// Variable to store the results in, if we get any
$results = [];
if ($condition != '') {
// We have a condition, let's prepare the query
$stmt = $pdo->prepare("SELECT * FROM list WHERE " . $condition);
// Let's execute the prepared statement and send in the value:
$stmt->execute($params);
// Get the results as associative arrays
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
变量$results
现在将包含基于条件的值,如果没有传递值,则包含一个空数组。
注意
我还没有测试这个确切的代码IRL,但逻辑应该是合理的。