I have a search query and when I search all like keywords work properly the records are showing with the matched criteria, but the problem is that where clause in not working.
$position = $this->session->set_userdata('position', $this->input->post('position'));
$adress_all = explode(",", $this->session->userdata('address'));
$this->db->like('address', $adress_all[0]);
$this->db->or_like('game', $this->session->userdata('skills'));
$this->db->or_like('gender', $this->session->userdata('coach'));
$this->db->or_like('Positions', $this->session->userdata('position'));
$this->db->where('type', 'private');//all other type coaches is also showing up
$sql = $this->db->get('coach');
You need to use Grouping LIKE of codeigniter
$this->db->group_start();
$this->db->like('address', $adress_all[0]);
$this->db->or_like('game', $this->session->userdata('skills'));
$this->db->or_like('gender', $this->session->userdata('coach'));
$this->db->or_like('Positions', $this->session->userdata('position'));
$this->db->group_end();
$this->db->where('type', 'private');
$sql = $this->db->get('coach');
Hope this works(need to test on your DB)
See Doc
Try below things.
$this->db->where('type', 'private');//all other type coaches is also showing up
$this->db->where("(address LIKE '%". $adress_all[0]."%' OR game LIKE '%".$this->session->userdata('skills')."%' OR gender LIKE '%".$this->session->userdata('coach')."%' OR positions LIKE '%".$this->session->userdata('position')."%')",null,false);
$sql = $this->db->get('coach');
Related
I recently added search box to search certain data on my database.
Im using php LIKE function.for the first time when i use LIKE function it took only one word and if that match any of contents then the results came out.and if i type more than one word it came zero results and it return a error that "No results".
And as i did a research i made my code it to thing.(Now it is allways searching only for the last word on the sentence that we enter for search.)]
In a example :
If type "car for sell" the query going to search for "Sell" .If there are any records match the query then it will exicutue (weather it is car or any other data.)
what i want to do iss to let it search for complete search where it matchs in the database.
For a example :
if i want to find "car for sell"
i want the query to execute only cars for sell in my cars category and so on.
here are my codes.
$getquery = $_GET['query'];
if(isset($_GET['query'])){
$getquery = $_GET['query'];
$queryexplode = explode(" ", $getquery);
foreach($queryexplode as $queryexplodenew){
$meta = $queryexplodenew;
}
$getdataquery = "SELECT `AdName`, `AdAccessLink`, `timestamp`, `Country`, `Category`, `Price`, `Photo1name` FROM freeadpostingdata WHERE AdName LIKE '%$queryexplodenew%' OR Country LIKE '%$queryexplodenew%' OR Category LIKE '%$queryexplodenew%' OR AdDescription LIKE '%$queryexplodenew%' ORDER BY timestamp DESC LIMIT 0, 25";
$resultsgetdata = mysql_query($getdataquery);
$countprodu= mysql_num_rows($resultsgetdata);
}
please help me to get this solved.
thank you
The reason you are only searching for the last word is because of this:
$queryexplode = explode(" ", $getquery);
foreach($queryexplode as $queryexplodenew){
$meta = $queryexplodenew;
}
You are iterating over each word in the query with each word being put in $queryexplodenew in turn (and then assigned to $meta for some reason). When the loop completes, the thing in $queryexplodenew will be the last element iterated over.
Yes, for your code, it will always search for the last word.
$getquery = $_GET['query'];
$modifiedKeyword = explode(" ", $getquery);
$str = implode("', '", $modifiedKeyword );
And change your query like the following:
$sql = "SELECT id FROM your_table WHERE keyword IN ('$str')";
I hope it will work for you.
so I have a blog system, and i want to build a section for "related news", I am not making a 'Tags' system but just simply searching and storing the current title of the article (which is pulled from the database) in a string and exploding it to be able to later put all the words into a query, that later query will search all titles in the database to find any of those words, and if it does, it will return the title in a list. Here is the relevant code:
// note to stackoverflow peeps, $row_object_title is just the title that is pulled form the database
$row_object_title_lower = strtolower($row_object_title);
$keywords = explode(" ",$row_object_title_lower);
Code that is run later on the page:
$keywords_imploded = implode("','",$keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ('$keywords_imploded')
Now i try to list the titles by printing the title out, but nothing is display.
I am sure there is matching titles in the database.
Thanks
Your array of keywords is generated with:
$keywords = explode(" ",$row_object_title_lower);
What if you have a title like "My Super Blog Post"? You're going to get:
$keywords = array( "My", "Super", "Blog", "Post" );
Later on, you query using those values imploded together:
$keywords_imploded = implode("','",$keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ('$keywords_imploded')
The SELECT query is going to look like this:
SELECT object_title FROM table WHERE object_title IN ( 'My', 'Super', 'Blog', 'Post' );
I don't think that's going to find anything.
You need to re-evaluate how you're handling the list of titles (I think that's what you're going for, right?).
It seems as though you have misunderstood how the IN clause works.
The IN clause will look for what is on the left in the list of values on the right. For example: WHERE id IN (2,3,5) - if id is in that list it will return true. In your case it is the opposite.
Something like this should work for what your after but there are likely to be better alternatives.
$sql = '';
foreach ($keywords AS $keyword)
{
if ($sql != '')
$sql .= ' OR ';
$sql .= "object_title LIKE '%$keyword%'";
}
$query = 'SELECT object_title FROM table WHERE '.$sql;
% is a wildcard.
Just please remember to escape the values first.
Try:
$keywords_imploded = join("','", $keywords);
$myquery = sql_query("SELECT object_title FROM table WHERE object_title IN ($keywords_imploded)
I'm having trouble with a search query.
I have two columns named 'artist' & 'title'. But for an autocomplete function I need a SQL query to search in these columns while someone is typing. There is a very simple solution I know of which is the following:
SELECT * FROM music WHERE artist LIKE '%".$term."%' OR title LIKE
'%".$term."%'
$term = textboxvalue
But this query has a couple of huge problems. Let's say the artist is 'DJ Test' and the title is 'Amazing Test Song'. If I type 'DJ' it works fine. But when I type 'DJ Amazing'. No search results were found. Obviously ofcourse but I can't figure how to fix it.
But that's not the only problem. If someone types in 'DJ Test - Amazing Test Song' it has to ignore the '-'.
So my question is, what does my search query look like when I can type anything like 'Amazing DJ Test' and still give back what I need?
Try something like this.
I think it should work but I haven't tested it.
$terms = explode(' ', $term);
foreach($terms as $term){
$query = SELECT * FROM music WHERE artist LIKE '%".$term."%' OR title LIKE '%".$term."%'
return $query;
}
Should hopefully work
You would have to make it split the search string up into words, then add those words as lookup criteria by appending them to the query.
First make an array that contains each individual word from the search string.
$search = 'DJ TEST Amazing Test Song';
$search_terms = explode(" ", $search);
Then alter the query for each search term:
foreach($search_terms as $search_term) {
//append OR to query with $search_term
$query .= "OR artist LIKE '%".$search_term."%' OR title LIKE '%".$search_term."%'";
}
Is there any way to check if a column is "anything"? The reason is that i have a searchfunction that get's an ID from the URL, and then it passes it through the sql algorithm and shows the result. But if that URL "function" (?) isn't filled in, it just searches for:
...AND column=''...
and that doesn't return any results at all. I've tried using a "%", but that doesn't do anything.
Any ideas?
Here's the query:
mysql_query("SELECT * FROM filer
WHERE real_name LIKE '%$searchString%'
AND public='1' AND ikon='$tab'
OR filinfo LIKE '%$searchString%'
AND public='1'
AND ikon='$tab'
ORDER BY rank DESC, kommentarer DESC");
The problem is "ikon=''"...
and ikon like '%' would check for the column containing "anything". Note that like can also be used for comparing to literal strings with no wildcards, so, if you change that portion of SQL to use like then you could pre-set the variable to '%' and be all set.
However, as someone else mentioned below, beware of SQL injection attacks. I always strongly suggest that people use mysqli and prepared queries instead of relying on mysql_real_escape_string().
You can dynamically create your query, e.g.:
$query = "SELECT * FROM table WHERE foo='bar'";
if(isset($_GET['id'])) {
$query .= " AND column='" . mysql_real_escape_string($_GET['id']) . "'";
}
Update: Updated code to be closer to the OP's question.
Try using this:
AND ('$tab' = '' OR ikon = '$tab')
If the empty string is given then the condition will always succeed.
Alternatively, from PHP you could build two different queries depending on whether $id is empty or not.
Run your query if search string is provided by wrapping it in if-else condition:
$id = (int) $_GET['id'];
if ($id)
{
// run query
}
else
{
// echo oops
}
There is noway to check if a column is "anything"
The way to include all values into query result is exclude this field from the query.
But you can always build a query dynamically.
Just a small example:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";
For your query it's very easy:
$ikon="";
if ($id) $ikon = "AND ikon='$tab'";
mysql_query("SELECT * FROM filer
WHERE (real_name LIKE '%$searchString%'
OR filinfo LIKE '%$searchString%')
AND public='1'
$ikon
ORDER BY rank DESC, kommentarer DESC");
I hope you have all your strings already escaped
I take it that you are adding the values in from variables. The variable is coming and you need to do something with it - too late to hardcode a 'OR 1 = 1' section in there. You need to understand that LIKE isn't what it sounds like (partial matching only) - it does exact matches too. There is no need for 'field = anything' as:
{field LIKE '%'} will give you everything
{field LIKE 'specific_value'} will ONLY give you that value - it is not partial matching like it sounds like it would be.
Using 'specific_value%' or '%specific_value' will start doing partial matching. Therefore LIKE should do all you need for when you have a variable incoming that may be a '%' to get everything or a specific value that you want to match exactly. This is how search filtering behaviour would usually happen I expect.
I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';