Notice: array to string conversion in line 23 - php

<?php
include 'db.inc.php';
//function that well return search results
//takes the keywords entered by user
function search_results ($keywords){
//code here
$returned_results= array();//array that will contain results
$where= ""; // constract of query for results
$keywords = preg_split ('/[\s]+/', $keywords);
//function split values by space
// (hello aya) is like ( hello aya )
$total_keywords = count($keywords);
//count number of words entered ex(ayoy adel =2 , a b c s = 4)
foreach ($keywords as $key=>$keyword){
$where .="`keywords` LIKE '%$keywords%'";
if ($key != ($total_keywords -1 )){
$where .= " AND " ;
}
}
$results = "SELECT `title` , `subject` , `id` FROM `` WHERE $where ; ";
}
//array begins from 0 , this erro
//$key=>$keyword key=0 , 1, 2 $keyword value in database
//
//
//
/*$sqlQuery= " SELECT `keywords` FROM `question` WHERE `keywords` LIKE `%hci%` AND `keywords` LIKE `%what%` ";
*/
?>

This line here:
$where .="`keywords` LIKE '%$keywords%'";
includes the $keywords variable which is an array, not a string. You probably meant to use the $keyword variable there.

Related

Search only reads one keyword: SQLSTATE[HY093]: Invalid parameter number

I'm having an issue with my search feature of my website. It's not handling search terms with more than one word. try a live example of the search bar problem over at http://mobile.mixtapemonkey.com/
search "It's Better This Way"
as soon as you type in B I get an error. other than that it works, what do you think the issue is?
if (empty($errors)) {
$name_explode = explode(' ', $name); // explode keywords to get each individual keyword, and put into array
$name_count = count($name_explode); // count keywords from array
foreach($name_explode as $name_single) {
$x++; // increment x each loop
$keyword = "%".$name_single."%";
$where .= '`keywords` LIKE :keyword'; // append to where clause
if ($name_count!=$x) {
$where .= ' AND '; // as long as keyword isn't the last, append AND.
}
}
$sql = "SELECT `name`, `thumb`, `id`, `title` FROM `mixtapes` WHERE ".$where." ORDER BY `id` DESC LIMIT 40";
$search = $db->prepare($sql); // perform query
$search->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$search->execute();
$search_num_rows = $search->rowCount(); // get number of rows (results) returned
Please check the code I have added.the reason you got that error is due to your foreach loop. In that loop you add :keyword everytime. But that count dont match with the bindParam value count. So I changed you code and posting below
if (empty($errors)) {
$name_explode = explode(' ', $name); // explode keywords to get each individual keyword, and put into array
$name_count = count($name_explode); // count keywords from array
$x = 0;
foreach($name_explode as $name_single) {
$x++; // increment x each loop
$keyword[':keyword'.$x] = "%".$name_single."%";
$where .= '`keywords` LIKE :keyword'.$x; // append to where clause
if ($name_count!=$x) {
$where .= ' OR '; // as long as keyword isn't the last, append AND.
}
}
$sql = "SELECT `name`, `thumb`, `id`, `title` FROM `mixtapes` WHERE ".$where." ORDER BY `id` DESC LIMIT 40";
$search = $db->prepare($sql); // perform query
$search->execute($keyword);
$search_num_rows = $search->rowCount(); //

MySqli query like any values in a PHP array

I have a PHP array containing values and I want to query the database to find any results where the ItemName contains any of the values in the array.
$current_item = 'Big Fancy Red Car';
$words = explode(' ',$current_item); // Array of words to search
And the query:
SELECT ID FROM store_accessories WHERE ItemName LIKE '%$words%'
How do I select the ID of any items in the table whose ItemName contains any of the values in the $words array?
You can do it like this:
First explode the value into an array:
$terms = explode(' ', $search_term);
Loop the array to add the LIKE
foreach ($terms as $term) {
$term = mysql_real_escape_string($term);
$likes[] = "field LIKE '%$term%'";
}
Add to the query:
$sql = "select * from table where";
$sql .= implode(' OR ', $likes);
You can get the LIKE like this directly, also substituting ' with '' and escaping _ and %:
$field = "ItemName";
$like = "$field LIKE '%".str_replace(
array("'" , "_" , "%" , " " ),
array("''", "\\_", "\\%", "%' OR $field LIKE '%"),
$currentItem)."%'";

Multiple keywords search

I'm getting trouble to add the search in my site. I cannot figure out the way to make it done.
I 've a table as follow:
TABLE A
id text
1 Hello there whats up. I'm trying to code.
2 there need to be this code
Now I want search using the
Keywords = hello code
And the results should provide me both the rows because both the rows contains some portion of the keyword as follow:
id text
1 **Hello** there whats up. I'm trying to **code**
2 there need to be this **code**
Also the result should provide the row with max number of keywords matched first.
I tried doing this but it only provide me some of my desire results.
<?php
$keyword = 'hello code';
$exloded = explode(' ', $keyword);
foreach($exploded as value):
$sth = $db->query("SELECT * FROM A WHERE `text` LIKE :value");
$sth->execute(array(':value' => '%'.$value.'%'));
$rows = $sth->fetchAll();
endforeach;
echo $rows;
?>
Updated
I simply Did this and it worked fine for me. But I want to know whether this is the correct way to get the work done.
$keyword = hello code;
$query ="SELECT *, MATCH(`page_content`) AGAINST('$keyword' IN BOOLEAN MODE) AS score FROM super_pages WHERE MATCH(`page_content`) AGAINST('$keyword' IN BOOLEAN MODE) ORDER BY score DESC";
$sth = $this->db->query($query);
$result = $sth->fetchAll();
$rows will have the data where your keyword code matches in your table you can rewrite your code to match for both keywords as
$keyword = 'hello code';
$exloded = explode(' ', $keyword);
$query = 'SELECT * FROM A ';
$i = 0;
$params = array();
foreach ($exploded as $value):
if ($i == 0) {
$query .= ' WHERE `text` LIKE :value_'.$i;
} else {
$query .= ' OR `text` LIKE :value_'.$i;
}
$params[':value_'.$i] = '%'.$value .'%';
$i++;
endforeach;
$sth = $db->query($query);
$sth->execute($params);
$rows = $sth->fetchAll();
echo '<pre>';print_r($rows);echo '</pre>';
Build your query in loop(over your provided keywords) and assign unique placeholders in query to match for all values
Edit for full text search
Using full text search you can match exact same phrase with provided keyword,In order to work with full text search you need an index of type FULLTEXT.
ALTER TABLE `A` ADD FULLTEXT INDEX `fulltextindex` (`text`);
And query will be like
$keyword = 'hello code';
$exloded = explode(' ', $keyword);
$where = '';
$i = 0;
$select = array();
$params = array();
foreach ($exploded as $value):
$select[]= ' MATCH(`text`) AGAINST(:value_'.$i.' IN BOOLEAN MODE) ';
if ($i == 0) {
$where .= ' WHERE MATCH(`text`) AGAINST(:value_'.$i.' IN BOOLEAN MODE)';
} else {
$where .= ' OR MATCH(`text`) AGAINST(:value_'.$i.' IN BOOLEAN MODE)';
}
$params[':value_'.$i] = $value ;
$i++;
endforeach;
$query ='SELECT *,'. implode( ' + ',$select).' AS score FROM A '.$where.' ORDER BY score DESC';
$sth = $db->query($query);
$sth->execute($params);
$rows = $sth->fetchAll();
echo '<pre>';print_r($rows);echo '</pre>';
Above code will produce a query like
SELECT *,
MATCH(`text`) AGAINST('hello' IN BOOLEAN MODE)
+
MATCH(`text`) AGAINST('code' IN BOOLEAN MODE) AS score
FROM A
WHERE MATCH(`text`) AGAINST('hello' IN BOOLEAN MODE)
OR MATCH(`text`) AGAINST('code' IN BOOLEAN MODE)
ORDER BY score DESC
Alias score in above query will have value for each row and its matched score thus you can order your result in descending manner to show the records first which has a highest score.
Note: You can use Full text search in Myisam but for innodb you have
to upgrade your Mysql to 5.6 which supports full text searching in
innodb too
you can use the following code:
<?php
$keyword = 'hello code';
$exloded = explode(' ', $keyword);
$sql = "SELECT * FROM A WHERE ";
foreach($exploded as $value):
$sql .= "text LIKE '" . $value "%' OR ";
endforeach;
// remove last 'OR '
$sql = substr($sql, -3);
$result = mysqli_query($con, $sql);
//................
?>

How to eliminate duplicate search results in MySQL?

I am having some trouble displaying text from database using PHP and SQL. Below is a script similar to what I have.
$search_split = explode(" ", $search); //$search is what user entered
foreach ($search_split as $searcharray) {
$searched = mysqli_query($connect, "SELECT * FROM people WHERE `description` LIKE '%$searcharray%'");
while($info = mysqli_fetch_array($searched)) {
echo $info['description'];
}
}
So, for example the user enter 'He is male'. I split the word into three part 'He', 'is' and 'male' using 'explode' function. After that, I search the database for words that is similar to those three word. However, if a row have all the three words, it would display the row three times. How can I make it to display only once?
You could do something like this:
$search = 'test search me';
$search_split = array_map(function($piece) use ($mysqli_connection){
return "'%" . $mysqli_connection->real_escape_string($piece) . "%'";
}, explode(' ', $search)); //$search is what user entered
$search_split = implode(' OR `description` LIKE ', $search_split);
$sql = "SELECT * FROM people WHERE `description` LIKE $search_split";
echo $sql; // SELECT * FROM people WHERE `description` LIKE '%test%' OR `description` LIKE '%search%' OR `description` LIKE '%me%'
$searched = mysqli_query($connect, $sql);
Can you use full text search?
Add a full text index to the table
ALTER TABLE people ADD FULLTEXT(description);
Then you can use a query like this
SELECT *
FROM people
WHERE
MATCH ( description )
AGAINST ('+He +is +male' IN BOOLEAN MODE)
First store your results into one array then display it. Refer below code.
$search_split = explode(" ", $search); //$search is what user entered
foreach ($search_split as $searcharray) {
$searched = mysqli_query($connect, "SELECT * FROM people WHERE `description` LIKE '%$searcharray%'");
while($info = mysqli_fetch_array($searched)) {
$results[$info['YOUR_PRIMARY_KEY']] = $info['description']; // this will over write your previous record
}
}
foreach($results as $result){
echo $result;
}
Now every records display only once.
You have put your db query in a foreach loop, which loops 3 times (with the current data: he, is and male). What you want to do is put all the search variables in one query, something like:
$search_split = explode(" ", $search); //$search is what user entered
$querypart = "'%" . implode("%' AND '%", $search_split) . "%'"; // use OR or AND, to your liking
$searched = mysqli_query($connect, "SELECT * FROM people WHERE `description` LIKE " . $querypart);
while($info = mysqli_fetch_array($searched)) {
echo $info['description'];
}
This does not take any escaping/sanitizing of the query input, be aware...
$result = array();
$search_split = explode(" ", $search); //$search is what user entered
foreach ($search_split as $searcharray) {
$searched = mysqli_query($connect, "SELECT * FROM people WHERE `description` LIKE '%$searcharray%'");
while($info = mysqli_fetch_array($searched)) {
$result[] = $info['description'];
}
}
$finalres = array_unique($result);
so, finalres contains unique results
for($i = 0; $i < count($finalres); $i++)
echo $finalres[$i];

mysql full text search not working

i am trying to work with MySQL full text search in table
query:
$text="MySQL HTML";
$sql="SELECT * FROM search
WHERE MATCH (title,title_info) AGAINST ('$text' IN BOOLEAN MODE)";
it is supposed to return all rows having both MySQL HTML or MySQL or HTML,
but its not resulting any thing why?
You must add + sign as prefix to each search term:
$text="MySQL HTML";
$text_array = split(' ',$text);
$search_terms = '+'.join($text_array,' +'); // +MySQL +HTML
$sql="SELECT * FROM search
WHERE MATCH (title,title_info) AGAINST ('$search_terms' IN BOOLEAN MODE)";
Read more about fulltext search:
http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html
Try this one
$text="MySQL HTML";
$sql=" SELECT * FROM search
WHERE title LIKE '%$text%' OR
title_info LIKE '%$text%'";
Try to implement this function will search full text
$text = "Test String For You";
$bquery .= getwQuery($text,'title,title_info');
$sql="SELECT * FROM search WHERE ".$bquery;
echo $sql;
function getwQuery($data, $field_name)
{
$names_exploded = explode(" ", $data);
$fname = explode(",", $field_name);
foreach($names_exploded as $each_name)
{
if($each_name != ""):
$bquery .= " AND (";
foreach($fname as $fn)
{
$bquery .= $fn." LIKE '%".$each_name."%' OR ";
}
$bquery = rtrim($bquery,' OR ');
$bquery .= ')';
endif;
}
$bquery = ltrim($bquery,' AND ');
return $bquery;
}
Output:
SELECT * FROM search WHERE (title LIKE '%Test%' OR title_info LIKE '%Test%') AND (title LIKE '%String%' OR title_info LIKE '%String%') AND (title LIKE '%For%' OR title_info LIKE '%For%') AND (title LIKE '%You%' OR title_info LIKE '%You%')

Categories