我有一个搜索表单,希望用户搜索多个术语。我目前正在使用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));
答案 0 :(得分:2)
您是否考虑过这样做:
$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。
答案 1 :(得分:1)
如果其他人也需要这个答案......
$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 ".$implode."");
$sql->execute(array(":term"=>"%".$term."%"));
答案 2 :(得分:1)
重拍
$my_explode = explode(" ",$search);
$query = array();
foreach($my_explode as $string)
{
$query[] ="name LIKE '%".$string."%' OR email LIKE '%".$string."%'";
}
$implode = implode(' OR ', $query);
foreach ($db->query("SELECT * FROM _table WHERE ".$implode."") as $info)
{
echo $info['name']."<br />";
}
安全注射,php只检索字母数字字符
$search = preg_replace("/[^a-zA-Z0-9]+/", "-", $_GET["text"]);