0

我有一个搜索输入,我将用户输入分解为数组(关键字)。

前任。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' 这两个词

4

2 回答 2

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();
于 2013-06-12T15:32:00.000 回答
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;
于 2013-06-12T15:27:13.083 回答