我有一个搜索表单,希望用户搜索多个术语。我目前正在使用 PHP PDO,并且仍在学习中...我想知道是否有人可以告诉我我在这里做错了什么。
$varSearch = @$_GET['dms'];
$varTerm = explode(" ", $varSearch);
$termArray = array();
foreach($varTerm as $term){
$term = trim($term);
if(!empty($term)){
$termArray[] = "name LIKE '%".$term."%' OR tags LIKE '%".$term."%'";
}
}
$implode = implode(' OR ', $termArray);
$sql = $dbh->prepare("SELECT * FROM table WHERE ?");
$sql->execute(array($implode));
最佳答案
您是否考虑过做这样的事情:
$varSearch = @$_GET['dms'];
$varTerm = explode(" ", $varSearch);
$termsStringArray = array();
$termsArray = array();
foreach($varTerm as $term){
$term = trim($term);
if(!empty($term)) {
array_push($termsStringArray, "name LIKE ? OR tags LIKE ? ");
array_push($termsArray, $term);
array_push($termsArray, $term); // note, you can do this part differently, if you'd like
}
}
$implodedTermsString = implode('OR ', $termsStringArray);
$sql = $dbh->prepare("SELECT * FROM biz WHERE " . $implodedTermsString);
$sql->execute(array($termsArray));
输出:
// prepare statement
SELECT * FROM biz WHERE name LIKE ? OR tags LIKE ? OR name LIKE ? OR tags LIKE ? OR name LIKE ? OR tags LIKE ? OR name LIKE ? OR tags LIKE ?
// $termsArray (for execute)
Array
(
[0] => this
[1] => this
[2] => is
[3] => is
[4] => the
[5] => the
[6] => string
[7] => string
)
基本上,尝试将数组数据与初始 SQL 查询 prepare
字符串分开。让我知道这是否适合您!
尽管如此,您仍然需要对从 $_GET
变量获取的数据进行某种检查(或清理)。该 $_GET
变量中可能包含任何内容...并且可能对 SQL injections 不利。或其他不需要的问题。
而且,LIKE
不一定是执行此类数据库搜索的最有效方法。但如果你使用它(我过去用它来搜索东西),请尝试查看:http://use-the-index-luke.com/sql/where-clause/searching-for-ranges/like-performance-tuning .
关于php - 带有爆炸/内爆的多术语 SQL 和 PHP PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9074441/