$tag = 'sky';
select rows where tags contains $tag:
$sql = "select * from images where tags like '%" . $tag . "%' order by date desc";
What if I have an array of tags:
$tags = array('sky', 'earth', 'sun'); // max 3
foreach($tags as $tag) {
$sql = "select * from images where tags like '%" . $tag . "%' order by date desc";
}
Is this the right way, especially regarding performances.
The table images has about 20.000 rows.
You can use regexp.
$sql = "select * from images where tags REGEXP '" . implode('|', $tags) . "' order by date desc";
Your final result will be:
select * from images where tags REGEXP 'sky|earth|sun' order by date desc
Here is a possible implementation, you don't have to know the array size.
$tags = array('one', 'two');
$sql = "select * from images where tags like '%" . implode("%' OR tags like '%",$tags) . "%' order by date desc";
Add multiple tags to your query using OR in your query
$sql = "select * from images where tags like '%" . $tag[0] . "%' OR tags like '%" . $tag[1] . "%' OR tags like '%" . $tag[2] . "%' order by date desc";
You don't need to use foreach to run query
UPDATE 1
$comma_separated = "('" . implode("','", $tags) . "')";
$sql = "select * from images where tags IN ".$comma_separated;
Most Efficient Way
A REGEXP might be more efficient, you have to benchmark it by your self
$sql = "select * from images where tags REGEXP '" . implode('|', $tags) . "' order by date desc";
Related
I wanna make this select with ORDER BY element and Limit Element But i cant solve it .. please help me..
I am doing a php chat bot tha find something on my database and reply ..but when i am selecting data it select many data in on time . thats whyy i nedd limit
$aKeyword = explode(" ",$keyword);
$query ="SELECT * FROM reply_key WHERE reply_key_value like '%" . $aKeyword[0] . "%' ";
for($i = 1; $i < count($aKeyword); $i++) {
if(!empty($aKeyword[$i])) {
$query .= "OR reply_key_value like '%" . $aKeyword[$i] . "%' ";
}
}
You can add order by id desc and then limit 1 to get the latest record, however, you can remove that "desc" if you want the oldest record.
$query ="SELECT * FROM reply_key WHERE reply_key_value like '%" . $aKeyword[0] . "%' " ORDER BY id desc LIMIT 1
i am using this sql search to find a title and artist in my database. I have on field containing infos like "ref.1570 title artist.mp4". When I do the search it works but in one direction only, i would like to get the result whatever the order i do the search... to be more precise if i search "title artist" no problem i found it. If i search "artist title" no way ... how can you help me making php sql search both directions ?
Best regards and thank you for your help.
Phil
i am using this code :
if ($search != null) {
$sql = 'SELECT * FROM `catalog` WHERE (`file`LIKE "%' . $search . '%")';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE (`file`LIKE "%' . $search . '%")';
}
Why don't you split keyword $search with space and append with Like statement in the query. Eg:
if ($search != null) {
$keywords=explode(" ",$search);
$sql = 'SELECT * FROM `catalog` WHERE 1=1'; // just to append OR condition.This won't affect anything as the condition will always be true.
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE 1=1 ';
foreach($keywords as $key){
if(!empty($key)){
$sql.=' And file Like \'%'.$key.'\%';
$sqlCount.=' And file Like \'%'.$key.'\%';
}
}
}
I believe this will work as you expected.
I think you won't get around a foreach:
if ($search != null) {
$arrayOfSearchTerms = explode(' ', $search);
$sql = 'SELECT * FROM `catalog` WHERE ';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE ';
$termNumber = 0;
foreach ($arrayOfSearchTerms as $term) {
$addingSql = '';
if ($termNumber > 0) {
$addingSql = ' OR ';
}
$addingSql .= '(`file` LIKE "%') . $term . '%")';
$sql .= $addingSql;
$sqlCount = $addingSql;
$termNumber++;
}
}
You need to iterate over your search terms and add this terms into your 'LIKE'-Statement
you can try this research: it does a LIKE %word% for every word. If you want more powerfull research you should use tools like elasticsearch etc...
This way you could do:
$parts = explode(" ",$search)
$queryParts = array();
foreach ($parts as $part) {
$queryParts[] = `artist`LIKE "%' . $part . '%" ;
}
// this way we can have like %artist% AND like %title%
$querySearch= implode(" AND ", $queryParts);
$sql = 'SELECT * FROM `catalog` WHERE (". $querySearch .")';
$sqlCount = 'SELECT count(*) FROM `catalog` WHERE (`". $querySearch .")';
you have solved my problem i know now hos to correctly explode a request into variables ..
$search = $name;
$explode=explode(" ",$search);
print_r (explode(" ",$explode));
and then i use my sql request like this
$sql = 'SELECT * FROM `catalog` WHERE (`idc` LIKE "%' . $search . '%" OR `file` LIKE "%' . $search . '%" OR `title` LIKE "%' . $explode[0] . '%" AND `artist`LIKE "%' . $explode[1] . '% " OR `artist`LIKE "%' . $explode[0] . '%" AND `title`LIKE "%' . $explode[1] . '%")';
and it is working !
COOL
Use the multi query functions,
in mysqli should be : mysqli_multi_query();
More info on : Mysqli Multiquery
I had just finished my search functionality for a users system when I found out that it didn't search the way I wanted it to.
If I have a datebase table with 2 columns called 'fname' and 'lname'.
In one row, 'fname' has a value of 'Ashley' and 'lname' has a value of 'Staggs'.
I can search for either 'Ashley' or 'Staggs' and I will get the results correctly, but if I search for 'Ashley Staggs', no results are displayed.
How would I do this properly?
My SELECT query is as follows:
SELECT * FROM `users` WHERE fname LIKE '%" . protect($_GET['s']) . "%' OR lname LIKE '%" . protect($_GET['s']) . "%'
I knew something like this would happen, but this time I can't figure it out.
Thanks,
Ashley
'Ashley Staggs' is neither in fname, nor in lname, so your request doesn't return anything. You could try to concatenate your MySQL fields:
SELECT * FROM `users` WHERE fname LIKE '%" . $_GET['s'] . "%' OR lname LIKE '%" . $_GET['s'] . "%' OR CONCAT(fname, ' ', lname) LIKE '%" . $_GET['s'] . "%'
[EDIT] Even better:
SELECT * FROM `users`
WHERE REPLACE(CONCAT(fname, lname, fname), ' ', '')
LIKE '%" . str_replace(' ', '', protect($_GET['s'])) . "%'
SELECT fname_lname FROM ( SELECT CONCAT(fname, ' ', lname) fname_lname FROM users ) users
WHERE fname_lname LIKE '%" . $_GET['s'] . "%'
You might try something like this - it'll just split the search string by spaces and search for each word:
$search = explode(' ', $_GET['s']);
$query = 'SELECT * FROM `users` WHERE 0';
foreach ($search as $v)
{
$v = mysql_real_escape_string($v);
$query .= " OR (`fname` LIKE '%{$v}%' OR `lname` LIKE '%{$v}%')";
}
// echo $query;
Regarding sp00m answer, I have a slightly different approach, but built on the same concept.
$search = preg_replace ( "/\s\s+/" , " " , $_GET['s']);
And then use this query:
"SELECT * FROM `users` WHERE CONCAT(fname, ' ', lname) LIKE '%" . $search . "%' OR CONCAT(lname, ' ', fname) LIKE '%" . $search . "%'"
EDIT
Just had an idea you could use. Basically, you could create two additional fields in the table - fname_lname and lname_fname , use the regex I mentioned before to get rid of unnecessary spaces, use explode() to check the word count. If you have two words, then you can use these two new fields, giving you only two conditions in the query. When you have only one word, you still have two conditions in the query.
hey i want to sugest a stronger more strong search but it required MyISAM table
code for this is
$q="you search string";
$searchArray = explode(" ", $q);
$query="SELECT * FROM cmusers WHERE MATCH (`firstname`, `lastname`, `email`) AGAINST ('";
$i=0;
foreach ($searchArray as $word) {
$query .= "+".$word."* ";
}
$query .= "' IN BOOLEAN MODE)";
$result=mysql_query($query) or die("Error founded:".mysql_error()."there is problem existing we feels a very great sorry");
$finded=mysql_num_rows($result);
working of this can be seen at http://www.funnenjoy.com
I will just do
SELECT * FROM users WHERE CONCAT(firstname, ' ', lastname) LIKE '%{$search}%'
I have a search engine type website. It takes the users input, stores the query as $q, explodes the query and searches the database. It then displays the results with the name and web address of each result.
For example, if i searched for "computer programming"... Stack Overflow, stackoverflow.com would be my result. However, it displays twice. (once for computer, and once for programming.)
I tried to solve this with the array_unique function, and it does not work.
any help would be appreciated.
// trim whitespace
$trimmed = trim($q);
// seperate key-phrases
$trimmed_array = explode(" ", $trimmed);
// remove duplicates
$clean_array = array_unique($trimmed_array);
//query dataabase
foreach ($clean_array as $trimm){
$query = mysql_query("SELECT * FROM forumlist WHERE `keys` LIKE '%" . mysql_real_escape_string($trimm) . "%' ORDER BY rating DESC, total_ratings DESC") or die(mysql_error());
Thank you!
//query dataabase
$query = 'SELECT * FROM forumlist ';
$where = array();
foreach ($clean_array as $trimm){
$where[] = " `keys` LIKE '%" . mysql_real_escape_string($trimm) . "%' ";
}
if(!empty($where)){
$query .= " WHERE ". implode(' OR ', $where);
}
$query .= " ORDER BY rating DESC, total_ratings DESC";
$result = mysql_query($query) or die(mysql_error());
I want to write a Mysql statement that selects all from a table(posting) where title is like $title except for the title of $title. Basically I want to display all related posting of a certain posting. I want the query to select all the postings in the table that has the title name in the title OR detail. But I don't want the posting to display in the related postings.
//pseudocode
$query="Select * From posting Where title,detail, like %$title% except $title";
how do I write the except part?
This is the code you need, although it will be better if you have the current post id and just have something like WHERE id != " . (int)$current_post_id . "
$title = mysql_real_escape_string($title);
$sql = "
SELECT *
FROM posting
WHERE
title LIKE '%" . $title . "%' AND
detail LIKE '%" . %title . "%' AND
title != " . $title . "
";
Here is the ID version, way better :)
$title = mysql_real_escape_string($title);
$sql = "
SELECT *
FROM posting
WHERE
title LIKE '%" . $title . "%' AND
detail LIKE '%" . %title . "%' AND
id != " . (int)$post_id . "
";
EDIT: If you want LIKE '%$title%' AND != '$title' then:
SELECT * FROM posting
WHERE title LIKE '%$title%' AND detail LIKE '%$title%' AND title != '$title';
else
SELECT * FROM posting
WHERE title LIKE '%$title%' AND detail LIKE '%$title%' AND title NOT LIKE '%$title%';
Are you sure that's correct? LIKE '%$title%' AND NOT LIKE '%$title%' is a contradiction.