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());
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
$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";
I'm working on a search query and i hit a little bump... So as you see in the code below, i'm adding values to a array to execute it later in the script, but it's not really working... So when i var_dumped all of this, it returned like it is supposed to but the :q was not changed to the value which was entered in the link.
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values[":q"] = $_GET['q'];
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values["q"] = $_GET['q']; // TRY WITHOUT COLON
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
You should not use colon in the place of $values["q"] = $_GET['q'];
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values["q"] = $_GET['q']; // TRY WITHOUT COLON
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
$query = "SELECT * FROM articles";
$values = array();
if(!empty($_GET['q'])) {
$query .= " WHERE MATCH (title) AGAINST (q IN NATURAL LANGUAGE MODE)";
$db->bindParam(':q', $_GET['q']);
}
$fullQuery = $query . " ORDER BY id DESC" . " LIMIT {$paginator->getLimitSQL()}"
$getArticles = $db->prepare($fullQuery)->execute();
So after a while i figured it out, You're not supposed to use parameters while binding in the query, and like #Poiz pointed out i shouldnt use colons in the array either
Thx to everyone who tried helping :)
$fields = array('surname', 'firstname', 'maiden', 'birth', 'death', 'obittext'); $conditions = array();
foreach($fields as $field){
if(isset($_POST[$field]) && $_POST[$field] != '') {
$conditions[] = "`$field` LIKE '%" . $_POST[$field] . "%'";
}
}
$sql = "SELECT * FROM obits ";
if(count($conditions) > 0) {
$sql .= "WHERE " . implode (' AND ', $conditions);
}
$result = mysqli_query($con, $sql);
So far this allows me to search either one or more than one field like a surname and/or a date of birth. What I would like to do is also sort this by relevance as it currently sorts by the primary ID (ex: I want smith to come before klingensmith if I search smith).
I am really new at this, getting this far required much gnashing of teeth so please explain like I'm 5. I already tried:
$result = mysqli_query($con, $sql, ' ORDER BY relevance DESC ');
which just broke it. I suspect I need to add another condition but I don't know what or where. Very much thanks, and much respect to all you people who understand this stuff.
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