search array of words in database - php

I have text :
$a = I wanna eat apple , and banana .
I wanna get every words and punctuation of that sentence :
$b = explode(' ', strtolower(trim($a)));
the result of explode is array.
I have a words table on db that has fields : id, word and typewords all in lowercase. but for punctuation there are no exist in db.
I wanna search every words in db to take the type of words, so the final result that i want to get is :
words/typeofwords = I/n wanna/v eat/v apple/n ,/, and/p banana/n ./.
here's the code :
function getWord ($word){
$i = 0 ;
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
while ($row = mysql_fetch_array($query)) {
$word[$i] = $row['typewords'];
$i++;
}
return $word;
}
echo $b.'/'.getWord($b);
but it doesn't work, please help me, thanks !

Try with this:
function getWord($words){
$association = array();
foreach($words as $word)
{
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
if($row = mysql_fetch_array($query))
$association[$word] = $row['typewords'];
elseif(preg_match('/[\.\,\:\;\?\!]/',$word)==1)
$association[$word] = $word;
}
return $association;
}
$typewords = getWord($b);
foreach($b as $w)
echo $w.'/'.$typewords[$w];

function getWord($word){
// concat the word your searching for with the result
// http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
$query = mysql_query("SELECT CONCAT(word,'/',typewords) as this_result FROM words WHERE word = '$word' ");
$row = mysql_fetch_array($query);
return $row['this_result']." "; // added a space at the end.
}
// loop through the $b array and send each to the function
foreach($b as $searchword) {
echo getWord($searchword);
}

You assume the function parameter to be an array, but it is a string.
Edit: In your function you treat $word as an array as well as a string. Decide what you want and recode your function.

Related

How to extract comma separated column values from database using php

In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php

PHP compare two arrays from different locations

I am wanting to compare two different arrays. Basically I have a database with phrases in and on my website I have a search function where the user types in a phrase.
When they click search I have a PHP page which 'explodes' the string typed in by the user and its put into an array.
Then I pull all the phrases from my database where I have also used the 'explode' function and split all the words into an array.
I now want to compare all the arrays to find close matches with 3 or more words matching each phrase.
How do I do this?
Well what I've tried totally failed, but here is what I have
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //user entered data
$search_term = str_replace ("?", "", $search_term); //removes question marks
$array = explode(" ", $search_term); //breaks apart user entered data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array) . " LIMIT 0,10";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title'];
$thetitle = str_replace ("?", "", $thetitle);
$title_array[] = $thetitle;
$newarray = explode(" ", $search_term);
foreach ($newarray as $key=>$newword) {
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value);
$contacts = array_diff_key($thenewarray, array_flip($newarray));
foreach($contacts as $key => $value) {
echo $newword."<br />";
echo $value."<br /><hr />";
}
}
}
But basically all I want is to display suggested phrases which are similar to what the user has already typed into the search box.
So If I searched "How do I compare two arrays that have the same values?", I would see 10 suggestions that are worded similar, so like "How to compare multiple arrays?" or "can I compare two arrays" etc...
So basically like when I first posted this question on this site, I got other questions that may help, thats basically what I want. This code im using was origionally to match just one word or an exact matching string, im editing it to find matching words and only show phrases with 3 or more matching words.
I don't think that this is the best solution for your search script. But I'll try to give you the answer:
<?php
$string1 = "This is my first string";
$string2 = "And here is my second string";
$array1 = explode(" ", $string1);
$array2 = explode(" ", $string2);
$num = 0;
foreach($array1 as $arr) {
if(in_array($arr, $array2))
$num++;
}
$match = $num >= 3 ? true : false;
?>
use array_intersect function
$firstArray = "This is a test only";
$secondArray = "This is test";
$array1 = explode(" ", $firstArray);
$array2 = explode(" ", $secondArray);
$result = array_intersect($array1, $array2);
$noOfWordMatch = count($result);
$check = $noOfWordMatch >= 3 ? true : false; ;

How would I sort this array [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to sort the results of this code?
Im making a search feature which allows a user to search a question and it will show the top 5 best matching results by counting the number of matching words in the question.
Basically I want the order to show the best match first which would be the question with the highest amount of matching words.
Here is the code I have.
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$search_count = str_word_count($search_term); //count words of string entered by user
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from
//user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found
{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
$percentage = '.5'; //percentage to take of search word count
$percent = $search_count - ($search_count * $percentage); //take percentage off word count
if ($matchingwords >= $percent){
$finalarray = array($title => $matchingwords);
foreach( $finalarray as $thetitle=>$countmatch ){
?>
<li><?php echo $thetitle ?><i> <br />No. of matching words: <?php echo $countmatch; ?></i></li>
<?php
}
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
When you search something it will show something like this.
Iv put the number of matching words under each of the questions however they are not in order. It just shows the first 5 questions from the database that have a 50% word match. I want it to show the top 5 with the most amount of matching words.
What code would I need to add and where would I put it in order to do this?
Thanks
Here's my take on your problem. A lot of things have been changed:
mysql_ functions replaced with PDO
usage of anonymous functions means PHP 5.3 is required
main logic has been restructured (it's really hard to follow your result processing, so I might be missing something you need, for example the point of that $percentage)
I realize this might look complicated, but I think that the sooner you learn modern practices (PDO, anonymous functions), the better off you will be.
<?php
/**
* #param string $search_term word or space-separated list of words to search for
* #param int $count
* #return stdClass[] array of matching row objects
*/
function find_matches($search_term, $count = 5) {
$search_term = str_replace("?", "", $search_term);
$search_term = trim($search_term);
if(!strlen($search_term)) {
return array();
}
$search_terms = explode(" ", $search_term);
// build query with bind variables to avoid sql injection
$params = array();
$clauses = array();
foreach ($search_terms as $key => $word) {
$ident = ":choice" . intval($key);
$clause = "`title` LIKE {$ident}";
$clauses []= $clause;
$params [$ident] = '%' . $word . '%';
}
// execute query
$pdo = new PDO('connection_string');
$q = "SELECT * FROM `posts` WHERE " . implode(' OR ', $clauses);
$query = $pdo->prepare($q);
$query->execute($params);
$rows = $query->fetchAll(PDO::FETCH_OBJ);
// for each row, count matches
foreach($rows as $row) {
$the_title = $row->title;
$the_title = str_replace("?", "", $the_title);
$title_terms = explode(" ", $the_title);
$result = array_intersect($search_terms, $title_terms);
$row->matchcount = count($result);
}
// sort all rows by match count descending, rows with more matches come first
usort($rows, function($row1, $row2) {
return - ($row1->matchcount - $row2->matchcount);
});
return array_slice($rows, 0, $count);
}
?>
<?php
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING);
$best_matches = find_matches($search_term, 5);
?>
<?php if(count($best_matches)): ?>
<ul>
<?php foreach($best_matches as $match): ?>
<li><?php echo htmlspecialchars($match->title); ?><i> <br/>No. of matching words: <?php echo $match->matchcount; ?></i></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<div id="search-status">No result found!</div>
<?php endif; ?>
Try adding asort($finalarray); after your $finalarray = array($title => $matchingwords); declaration:
...
if ($matchingwords >= $percent){
$finalarray = array($title => $matchingwords);
asort($finalarray);
....
It should sort your array Ascending by the Values

Remove last comma or prevent it from being printed at all MySQL/PHP

I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?
I did try to use rtrim, but I did not probably do it right.
This is my code as it is today:
<?php
$query0 = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()";
$result0 = mysql_query($query0);
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keyword = $row0['LCASE(ord)'];
echo "$keyword, ";
?>
I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )
$keyword = $row0['LCASE(ord)'];
$keywordc = "$keyword, ";
$keyword- = rtrim($keywordc, ', ');
echo "$keyword-, ";
As you might imagine, this did not print much (but at least it did not leave me with a blank page...)
I would do:
$keywords = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keywords[] = $row0['LCASE(ord)'];
}
echo implode(',', $keywords);
I usually do this by placing the results in an array first
$some_array = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {
$some_array[] = $row0['LCASE(ord)'];
}
then simply:
echo "My List: " . implode(', ', $some_array);
// Output looks something like:
My List: ord1, ord2, ord3, ord4
substr($string, 0, -1);
That removes the last character.

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.

Categories