I have a problem in creating advanced search with custom query and using $wpdb->get_results($query , OBJECT);
In Normal search in wordpress when we search xxx yyyy or search yyyy xxx we have same results and it's good.
But when I am forced to use query to create an advanced search then sequence of words in search fields are important and further xxx yyyy or search yyyy xxx aren't same result.
I want to say with an example:
I create two input field one for Title and another for Author of my posts(Author is an example only and in this place is a custom fields )
I try to read these fields and search them in wordpress
<?php
$t = $_REQUEST['title'];
$a = $_REQUEST['author'];
global $wpdb;
$query = "SELECT DISTINCT wp_posts.* FROM wp_posts, wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id";
if ($t != '') {
$t_sql = " AND wp_posts.post_title like '%$t%' ";
}
if ($a != '') {
$a_sql = " AND wp_postmeta.meta_key = 'Author' AND wp_postmeta.meta_value like '%$a%' ";
}
$query .= $t_sql;
$query .= $a_sql;
$pageposts = $wpdb->get_results($query , OBJECT);
global $post;
if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
//...
endforeach;
endif;
?>
In Your idea, What do I must to do?
You can split up your search terms by a Space character and then construct your query to look up every possible order of the words. Here is an example for your Title field:
// Assuming the title is "One Two Three"
$t = $_REQUEST['title'];
// Split the TITLE by space character
$terms = explode(' ', $t); // $terms = ["One", "Two", "Three"]
// Concats each search term with a LIKE operator
$temp = array();
foreach ($terms as $term) {
$temp[] = "title LIKE '%".$term."%'";
// $temp = ["title LIKE %One%", "title LIKE %Two%", ...
}
// Adds an AND operator for each $temp to the query statement
$query = "SELECT * FROM titleTable WHERE (".implode(' AND ', $temp).")";
// $query = SELECT * FROM titleTable WHERE
// (title LIKE '%One%' AND title LIKE '%Two%' AND title LIKE '%Three%')
Making custom query which search in the WP DB is not a good way. Use the WP_Query to do this.
Here is a link where someone was experiencing the same problem:
https://wordpress.stackexchange.com/questions/18703/wp-query-with-post-title-like-something
Actually, I've review your code on web developer portals, specially the SQL queries. And I also didn't knew why by searching xxx yyyy and yyyy xxx aren't same result with your PHP script. But the only tips that I can give to you:
$query .= $t_sql;
$query .= $a_sql;
// is to add an sql order by keyword like this
$query .= " ORDER BY wp_posts . post_title ";
Give it a try! And don't forget to addslashes() when you used $_GET, $_POST or $_COOKIE variable if the PHP of your server doesn't runs addslashes() on those variables. You can check this by using the function get_magic_quotes_gpc().
Related
I was trying to make a search engine so far I had done with it and the feature I lack in it was, when user queries a long sentence or two or three words with on not in line-wise in my DB is not going to show and it shows 0 results.
So far it is working fine with the one-word search it is doing a great job with that.
public function getResultsHtml($page, $pageSize, $term){
$fromLimit = ($page - 1) * $pageSize;
//page 1: (1-1) * 20
//page 2:(2-1) * 20
$query = $this->con->prepare("SELECT *
FROM sites WHERE title LIKE :term
OR url LIKE :term
OR keywords LIKE :term
OR description LIKE :term
ORDER BY clicks DESC
LIMIT :fromLimit,:pageSize");
$searchTerm = "%" . $term ."%";
$query->bindParam(":term",$searchTerm);
$query->bindParam(":fromLimit",$fromLimit,PDO::PARAM_INT);
$query->bindParam(":pageSize",$pageSize,PDO::PARAM_INT);
$query->execute();
$resultsHtml ="<div class='siteResults'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$id = $row["id"];
$url = $row["url"];
$title = $row["title"];
$description = $row["description"];
$title = $this->trimField($title,55);
$description = $this->trimField($description,230);
$resultsHtml .="<div class='resultContainer'>
<h3 class='title'>
<a class='result' href='$url' data-linkId='$id'>
$title
</a>
</h3>
<span class='url'>$url</span>
<span class='description'>$description</span>
</div>";
}
$resultsHtml .= "</div>";
return $resultsHtml;
}
So when user searches apple it is retrieving the data and we can see the search result in "apple store search" in the first image.But in second image when we search "apple search" it should be able to show us the "apple store search".
first image
Second image
First you need to breakdown your $term into separated words. With European languages, you can simply use explode:
<?php
$terms = explode(' ', $term);
// lets say your $term is 'apple orange lemon banana'
// $terms would be ['apple', 'orange', 'lemon', 'banana']
Prepare Terms List for Binding
Then, I'd build a key-value array for the terms binding:
<?php
// build a term list with term key (:term{number}) and associated term
// for binding
$term_params = [];
foreach ($terms as $key => $term) {
$term_params[":term{$key}"] = "%{$term}%";
}
// $term_params would be:
// [
// ':term0' => '%apple%',
// ':term1' => '%orange%',
// ':term2' => '%lemon%',
// ':term3' => '%banana%',
// ]
Prepare the Where Clause in SQL for Binding
Now, supposed the logics is all the terms need to show up in either of the target fields:
<?php
// a list of fields to search from
$fields = ['title', 'url', 'keywords', 'description'];
// build a where clause SQL based on the terms and fields
$or_where_clauses = [];
foreach (array_keys($term_params) as $term_key) {
$or_where_clauses[] = implode(' OR ', array_map(function ($field) use ($term_key) {
return "{$field} LIKE {$term_key}";
}, $fields));
}
$where_clauses_sql = implode(' AND ', array_map(function ($term_clause) {
// quote each term clause with bracket for proper OR logic to work
return '(' . $term_clause . ')';
}, $or_where_clauses);
The resulting where clauses sql would be:
(title like :term0 OR url like :term0 OR keywords like :term0 OR description like :term0)
AND
(title like :term1 OR url like :term1 OR keywords like :term1 OR description like :term1)
AND
...
...
(title like :termN OR url like :termN OR keywords like :termN OR description like :termN)
Putting Everything Together
I can then build the SQL string and bind the terms to the query accordingly:
<?php
// prepare the select statement
$query = $this->con->prepare("SELECT *
FROM sites WHERE {$where_clauses_sql}
ORDER BY clicks DESC
LIMIT :fromLimit,:pageSize");
// bind the terms
foreach ($term_params as $key => $value) {
$query->bindParam($key, $value);
}
$query->bindParam(":fromLimit", $fromLimit, PDO::PARAM_INT);
$query->bindParam(":pageSize", $pageSize, PDO::PARAM_INT);
$query->execute();
// ...
Shortcomings and Potential Solution
Please note that this approach does not understand the number of occurrence of terms in the field. And the way to separate words is far from perfect. For example:
It didn't handle punctuation marks.
It couldn't search for plural terms with the singular, or visa verse.
It could be matching part of a word by mistake (e.g. search "sing" and match "dressing").
It couldn't deal with CJK or languages without space).
You can use software like Elastic Search for better feature. With plugin and proper config, you can give even sort results with relevance, or give different field a different importance in the search process etc.
But that is an entirely different software than SQL server to use. You'd need to learn and plan how to index your contents there as well as just saving your data to SQL.
we dont know how u get search words from user, but as i guess u get them as an array. so you can try below code:
<?php
...
$textSearch = "";
for($i = 0 ; $i< count($userInputs);$i++){
if($i !== count($userInputs) -1){
$userInputData = $userInputs[$i];
$textSearch .= "'%$userInputData%' OR";
}else{
$textSearch .= "'%$userInputData%'";
}
}
and put $textSearch into your query.
remember , $userInputs is an array that u had before.
UPDATE
as your images shown, you can add $userInput = explode(" ",$textFromUser) in very begin of given code.
I want to create code to filter my catagory and tag, I'm using select box to filter, my code like this:
if ($filter2) {
$addedCondition = " AND (nama_kat LIKE '%$filter2%' OR nama_tag LIKE '%$filter2%') ";
}
$query = $db->prepare("SELECT * FROM konten
WHERE (nama_kat LIKE '%$filter1%'
OR nama_tag LIKE '%$filter2%') ".$addedCondition."
ORDER BY 'date' DESC");
work if I'm only filter one word, but once I filter with two words it's not working, my web displaying all articles.
you can try filter here http://stanime.pe.hu/
You have to explode your string into words and use OR.
$addedCondition = '';
$filter2 = explode(' ',$filter2);
foreach($filter2 as $word)
{
$addedCondition .= " OR (nama_kat LIKE '%$word%' OR nama_tag LIKE '%$word%') ";
}
I have a mysql query which simply looks into mysql to find LIKE strings and displays the result.
Within the same mysql query, I have 2 LIKE.
1 is always a single string and the other one can be single and sometimes multiple strings separated by commas.
when I use my code, I get no results at all even though I have all the fields in the mysql database and I also have all the search strings in the columns.
This is my code:
$area = 'London';
$res = 'santandar, HSBC, RBS, ';
$sql = "SELECT * FROM banks WHERE location LIKE '%$area%' AND name LIKE '%$res'";
I also tried it with preg_match and it didn't return anything:
$sql = "SELECT * FROM banks WHERE location LIKE '%$area%' AND name LIKE '".preg_match($res)."'";
If I remove the second LIKE and my code looks like below, it works just fine:
sql = "SELECT * FROM banks WHERE location LIKE '%$area%'";
So the issue starts when I try to search using a comma separated string.
Could someone please advise on this issue?
EDIT:
The PHP varibles are POSTS so they can be anything in each post.
they are like so:
$area = $_POST['area'];
$res = $_POST['res'];
you should use an OR condition:
$res_array = explode(',' $res)
$num_elem= count($res_array) // with this value you can build dinamically the query
"SELECT * FROM banks WHERE location LIKE '%$area%'
AND ( name LIKE concat('%', $res_array[0]),
OR LIKE concat('%', $res_array[1])
OR LIKE concat('%', $res_array[2]) ";
You are going to need to blow this out into separate LIKEs with an OR, such as:
...WHERE location LIKE '%{$area}' AND (name LIKE '%{$name1}%' OR name LIKE '%{$name2}' OR ...)
You could write this fairly simply with some PHP logic:
function build_like_or( $values, $field_name ) {
// Create an array from the comma-separated values
$names = explode( ',', $values );
// Trim all the elements to remove whitespaces
$names = array_map( 'trim', $names );
// Remove empty elements
$names = array_filter( $names );
$where = array();
// Loop over each, placing the "LIKE" clause into an array
foreach( (array)$names AS $name ) {
$where[] = "{$field_name} LIKE '%{$name}%'";
}
// Glue up the LIKE clauses.
$where = '(' . implode(' OR ', $where) . ')';
// Results will be something like:
// $where = "(name LIKE '%santadar%' OR name LIKE '%HSBC%')"
return $where;
}
Usage:
$area = 'London';
$res = 'santandar, HSBC, RBS, ';
$name_where = build_like_or( $res, 'name');
$sql = "SELECT * FROM banks WHERE location LIKE '%$area%' AND {$name_where}";
// echo $sql outputs "SELECT * FROM banks WHERE location LIKE 'London' AND (name LIKE '%santadar%' OR name LIKE '%HSBC%' OR name LIKE '%RBS%')
My code let me perform search, as long as the order of the words is correct.
Let's say I'm searching for big dog, but I also want to search for dog big. It get more complicated with 3 or more words.
Is there a way to create a SQL query which would let me search through values with any order?
Only way I can think of this is by having multiple queries, where I change order of PHP variables manually...
<?php
if(isset($_GET['query']) && !empty($_GET['query'])) {
$query = $_GET['query'];
$query_array = explode(' ', $query);
$query_string = '';
$query_counter = 1;
foreach($query_array as $word) {
$query_string .= '%' . $word . (count($query_string) == $query_counter++ ? '%' : '');
}
$query = "SELECT * FROM pages WHERE Name LIKE '$query_string'";
$result = sqlsrv_query($cms->conn, $query);
while($row = sqlsrv_fetch_array($result)) {
extract($row);
echo ''.$Name.'<br>';
}
sqlsrv_free_stmt($stmt);
}
else {
//echo 'NO GET';
}
?>
You could assemble your conditions and check for each word on it's own:
$query_array = explode(' ', $query);
$queryParts = array();
foreach ($query_arra AS $value){
$queryParts[]="Name like '%".mysql_real_escape_string($value)."%'";
}
$searchString = implode(" AND ", $queryParts);
The Search string would now be Name like '%big%' AND Name like '%dog%' ... depending on how much search-keywords have been there.
I use the same approach very often, also when it is required that ALL keywords appear in at least ONE of the columns. Then you need one more loop to create the required AND conditions:
$search = "Big Dog";
$keywords = explode (" ", $search);
$columns = array("Name", "description");
$andParts = array();
foreach ($keywords AS $keyword){
$orParts = array();
foreach($columns AS $column){
$orParts[] = $column . " LIKE '%" . mysql_real_escape_string($keyword) . "%'";
}
$andParts[]= "(" . implode($orParts, " OR ") . ")";
}
$and = implode ($andParts, " AND ");
echo $and;
this would produce the query part (Name like '%Big%' OR description like '%Big%') AND (Name like '%Dog%' or description like '%Dog%')
So, it will find any row, where dog and big are appearing in at least one of the columns name or description (could also be both in one column)
Since your original querystring is something like %big%dog%, so I assume you are okay with matching big wild dog. In this case, you can just use the AND operator.
(Name LIKE '%big%" and Name LIKE '%dog%")
myisam supports full text search:
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
One thing you could look into is Full Text Search for ms sql server.
https://msdn.microsoft.com/en-us/library/ms142571.aspx
it's similar to a "search engine" in that it works off of an algorithm to rank results and even similar words (think thesaurus type lookups)
It's not exactly trivial to set up, but it's easy enough to find a tutorial on the subject and how to query from FTS (as the syntax is different than say LIKE '%big%dog%')
Here's a sample query from the page linked above:
SELECT product_id
FROM products
WHERE CONTAINS(product_description, ”Snap Happy 100EZ” OR FORMSOF(THESAURUS,’Snap Happy’) OR ‘100EZ’)
AND product_cost < 200 ;
As I am learning PHP, naturally, I decided to create a search feature on my webpage. However I wanted to make mine more unique, so rather than using just a simple html input field as the 'search' field, I created two html select tags which allow the user to select two options and search based upon that. I managed to get the php to generate the search query, however it wasn't the sql query I wanted. My php code managed to generate a query hat looked like this: .com/results.php?option1=london&option2=car whereas ideally I want it to generate something like this: .com/results.php?combinedoptions=london+car
I've researched thoroughly into this and I hate to ask, what may be, a very simple question on this site.
$input = $_GET['input'];
$topic = $_GET['topic'];
$location = $_GET['location'];
$combined = $input . $topic . '' . $location;
$terms = explode(" ", $combined);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%'";
else
$query .= "OR keywords LIKE '%$each%'";
}
You would just split the incoming string. Here's a piece of code:
<?php
$combinedoptions = 'london+car';
$array = explode("+", $combinedoptions);
if (sizeof($array) != 2) { /*problem here*/ echo 'bad parameters'; return; }
$option1 = $array[0];
$option2 = $array[1];
?>
Just using the explode() method. Compiled code.