我有一个搜索输入,我将用户输入分解为数组(关键字)。
离。 web programmer
- > $search[0]=>web
,$search[1]=>programmer
如何将数组循环到搜索查询中?
$nums=count($search);
for($n=0; $n<$nums; $n++){
$SQL=$db->prepare("SELECT * FROM post
WHERE title LIKE :search_1 OR classify LIKE :search_2");
$SQL->bindValue(':search_1', "%".$search[$n]."%", PDO::PARAM_STR);
$SQL->bindValue(':search_2', "%".$search[$n]."%", PDO::PARAM_STR);
$SQL->execute();
}
$db=NULL;
所以它将从db
中搜索'web'和'programmer'这两个单词答案 0 :(得分:3)
这样的事情:
$strSQL="SELECT * FROM post WHERE 1=1 ";
foreach ($search as $i => $value){
$strSQL.=" AND (title LIKE :search_$i OR classify LIKE :search_clasify_$i)";
}
$SQL=$db->prepare($strSQL);
foreach ($search as $i => $value){
$SQL->bindValue(":search_$i", "%".$value."%", PDO::PARAM_STR);
$SQL->bindValue(":search_clasify_$i", "%".$value."%", PDO::PARAM_STR);
}
$SQL->execute();
答案 1 :(得分:1)
bindParam //you dont need to re-prepare every loop counter just do it once thats the whole point of prepare!
$SQL=$db->prepare("SELECT * FROM post WHERE title LIKE :search_1 OR classify LIKE :search_2");
//now loop and bind each set of vars and then execute inside the loop
for($n=0; $n<count($search); $n++){
$SQL->bindParam(':search_1', "%".$search[$n]."%", PDO::PARAM_STR);
$SQL->bindParam(':search_2', "%".$search[$n]."%", PDO::PARAM_STR);
$SQL->execute(); // you may find you need to pass the return result into an array which you can loop through afterwards or echo out the contents of each query on each count of this loop
}
$db=NULL;