PHP mysql query judge and not echo the repeart part
I want to make a php search query. First, I put a sentence and explode every word get $name
,Then I put $name
make a query to match all the name which is exist in my database. Then echo part $row['name'][$i]
has some word repeat.
for example: the sentence is :Marc Gasol is the brother of Pau Gasol
and Gasol
in my database, so the match words Gasol
apearl 2 times. how to echo $row['name'][$i];
and get only one Gasol
? thanks,
$query = mysql_query("SELECT * FROM books WHERE name like '$name[0]' OR name like '$name[1]' OR name like '$name[2]' OR name like '$name[3]' ");
$i = 0;
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
$sentence = "Marc Gasol is the brother of Pau Gasol";
$words = preg_split("/\s+/", $sentence);
//this will uniqueify your value set
$uniqueWords = array_keys(array_flip($words));
foreach($uniqueWords as $word){
$parts[] = "name like '%".mysql_real_escape_string($word)."%'";
}
$where = implode(" OR ", $parts);
$query = mysql_query("SELECT * FROM books WHERE $where ");
$i = 0;
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
You could run another quick loop through your array and remove all duplicate words before you proceed to executing your sql query that way you don't search the name twice in the first place. That should work if I am understanding what you are wanting to do.
精彩评论