1

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++; 
}       

2 Answers 2

2
$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++; 
} 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.