简体   繁体   中英

Assigning multiple keywords to PHP/MySQL keyword based search

I have a PHP keyword search script that searches a MySQL database and then displays the results. Currently, the script finds results based on a single keyword attached to a field in a MySQL database.

My question is; how can I attach multiple keywords to one field and return results if one or more of those keywords is matched in the users query?

Can I define the keywords in my database and separate them with commas? eg this, would, be, in, the, field

<?php

mysql_connect("localhost","username","password");
mysql_select_db("database");

if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM questions WHERE `keywords` LIKE '%{$query}%'  LIMIT 1";
$searchResult=mysql_query($searchSQL);

while($row=mysql_fetch_assoc($searchResult)){
$results[]="{$row['result']}";
}

echo implode($results);
}

?>

Either use a fulltext index , or split the keyword list into a compound "where like ... or like ... or like ..." statement:

$keywords = explode(' ', $_GET['q']);
$likes = array()
foreach($keywords as $kw) {
   $kw = mysql_real_escape_string($kw);
   $likes[] = "keywords LIKE '%{$kw}%'";
}

$sql = "SELECT ... WHERE " . implode(' OR ', $likes);

Storing compound data in a single field in a relational database is rarely a good idea, especially if you're going to need to access sub-portions of the whole field. Keywords should be stored in a separate table, one keyword per record. You can then use a link table to relate multiple keywords to each individual record in your parent table.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM