php - how to find text in a string from database? - php

Let's say i have:
$title = "Rihanna - Man Down";
and a database multiple rows including one with a field called "name" with the "Rihanna" value
now... how can i check if in $title exists "Rihanna" and if it does how to add a link on "Rihanna" like this:
with other words check if one of the expresions from $title exists the database
i think this second formulation it is better
Rihanna - Man Down
I want to do something like youtube does at some of it;s music videos to be more clear

If I understood correct, this can do the work:
Then first search in DataBase, your query must be something like this:
//Search for word in DataBase on filed "name"
$title = "Rihanna - Man Down";
$arr = explode('-', $title);
$title = $arr[0];
$result = mysql_query("SELECT name FROM table WHERE name LIKE '%" . mysql_real_escape_string($title) . "%'");
//If find results, then we replace and generate links in this loop
while($row = mysql_fetch_array( $result )) {
$str = str_replace($title, ''.$title.'', $row['name']);
echo $str; //Rihanna - Man Down
}

$words = explode("-", $title);
$result = array();
foreach ($words as $word)
{
$word = trim($word);
$res = mysql_query("SELECT name FROM table WHERE name='" . mysql_real_escape_string($word) . "'");
if (mysql_num_rows($res) > 0)
{
$result[] = '' . $word . '';
}
else
{
$result[] = $word;
}
}
$result = implode($result, " - ");
This will however also link to "artist?id=Pink" if a song from another artist is named Pink, but you have the artist Pink in your database.

Split your title into words, and for each word check if your database contains row with that name. If yes, replace occurences of the word with link.
foreach (preg_split("/\s+/", $title) as $word) {
if (word_in_database($word)) {
$title = str_replace($word, "$word", $title);
}
}

Related

select where id in csv string - how to do something if row is missing

I have a csv string and need to select rows having corresponding id.
And need to do something specific if a row doesn't exist.
$str = '1,2,3,4,5,6,7,8,9,10,11,12';
$st = $db->query("select *
from arts
where id in (" . $str . ")
order by field (id, " . $str . ")");
$arr = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($arr as $el) {
// if ($el is missing) {echo 'the row is missing';} // how to do this?
else { ... }
}
The easiest option here, assuming you are stuck with the input CSV string, is to use FIND_IN_SET, something along these lines:
$sql = "SELECT id, FIND_IN_SET(id, :list) AS result FROM arts";
$str = "1,2,3,4,5,6,7,8,9,10,11,12";
$stmt = $db->prepare($sql);
$stmt->bindParam(':list', $str);
$stmt->execute();
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($arr as $el){
if ($el["result"] <= 0) {
echo "the row is missing for id " . $el["id"];
}
}
Rather than look at the records found, this code first keys the retrieved records on the id and then looks through the ID's you are looking for and if this record isn't found (using isset()) then process the not found part...
$arr = array_column($arr, null, "id");
$ids = explode(",", $str);
foreach($ids as $el){
if(!isset($arr[$el])) {
echo 'the row is missing';
} else{
echo 'the row is there';
}
}

Search mysql database by phrase or seperate key words

Ok so when a user types their search phrase in the search input, I would like it to match the exact phrase or the key words entered.
I.e
So the title of a post is "Search the Database"
$searchVal = "Search database";
WHERE post_title LIKE '%" . $searchVal . "%'
The above code doesn't find a match as the title has "the" between Search Database.
How could I get it to match.
I thought maybe using explode but Im getting an error:
$sVals = explode(" ", $searchVal);
foreach ($sVals as $s) {
$querySearchVals .= "OR post_title LIKE '%" . $s . "%'";
}
Hope that makes sense.
Cheers
Maybe this could help
$search_key = $_POST['searchkey']; //take the search text from the post method
$search_words = array();
$search_words = explode(" ",$search_key);
$q_string = "";
$last_index = intval(count($search_Words)) - 1;
for($i = 0; $i<count($search_Words);$i++)
{
$q_string = $q_string . " post_title LIKE '%$search_words[$i]%' ";
if($i != $last_index)
$q_string = $q_string . " OR ";
}
And to make it even more accurate, you may skip the articles like A, The, An etc
You may want to insert the % in between the words and execute with 1 where clause. some thing like below should work.
$searchVal = "Search database";
$querySearchVals = "post_title LIKE '%";
$sVals = explode(" ", $searchVal);
foreach ($sVals as $s) {
$querySearchVals .= $s."%";
}
$querySearchVals .= "'";
echo $querySearchVals;
Hope it helps!

search array of words in database

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.

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