Need help with my php search for multiple keywords, the code below displays no results, but when I remove the explode function and foreeach construct, it works, but only displays results of 1 keyword.
For example, I have a list of keywords in a column: apple, red, blue, book, yellow bird.
Using the code below, if I typed red apple in the search box it would yield no results, I'd like for it to display all results containing the keyword I typed. Thanks
$search = $_POST['search'];
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim ($search);
$search = explode(",",$search);
$query=$db->prepare("SELECT * FROM thread WHERE title like '%".$search."%' OR keyword like '%".$search."%' OR description like '%".$search."%'");
foreach($search as $k)
{$query=$db->prepare("OR keyword LIKE '%$k%' OR title LIKE '%$k%' OR description LIKE '%$k%'");}
$query->execute(array('title' => $search, 'description'=>$search, 'keyword'=>$search));
$query->setFetchMode(PDO::FETCH_ASSOC);
$List="";
if($query->rowCount()<1)
{$List.="<div class='containerr'>No results found.</div>";}
else
{
while($row=$query->fetch())
{
$vid=$row['id'];
$user=$row['username'];
$preview=$row['preview'];
$names=$row['names'];
$good=$row['good'];
$date=$row['date'];
$date=date('M-d-Y', strtotime($date));
$title=$row['title'];
$List.='<div class="LISTT"><a href="mp.php?id='.$vid.'">'.$preview.'<br/>
<label>'.$title.'</label><br/>
<label style="color:black;">Added:</label> <label style="color:#666666">'.$date.'</label></a></div>';
}
The problem is, that you overwrite your SQL instead of appending to it. In addition to that, you run the title search for the redundant combined value, which I guess is not what you want. Try this:
$search = $_POST['search'];
$search = strtoupper($search);
$search = strip_tags($search);
$search = explode(",",$search);
$sql=array("SELECT * FROM thread WHERE ");
foreach($search as $k) {
$k=trim($k);
$sql[]="keyword LIKE '%$k%' OR title LIKE '%$k%' OR description LIKE '%$k%'";
}
$sql=implode(' OR ', $sql);
$query=$db->prepare($sql);
$query->execute(array());
$query->setFetchMode(PDO::FETCH_ASSOC);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.