Codeigniter auto-update search with %LIKE% - php

I am new to codeigniter. I have done auto suggest search using simple mysql but not with codeigniter's active records. It's very confusing to me.
My mysql format was :
$s = $_POST['s'];
$search_result = explode(' ', $s);
$query_temp = '';
$i=0;
foreach($search_result as $search){
$i++;
if($i == 1){
$query_temp .= "title LIKE '%$search%' OR description LIKE '%$search%' OR keywords LIKE '%$search%' OR link LIKE '%$search%'";
}else{
$query_temp .= "OR title LIKE '%$search%' OR description LIKE '%$search%' OR keywords LIKE '%$search%' OR link LIKE '%$search%'";
}
}
$search_query = mysql_real_escape_string(htmlentities($_POST['s']));
$run = mysql_query("SELECT * FROM search WHERE $query_temp")or die(mysql_error());
But here I have to search from 3 tables. I have no idea how to do it in this format in codeigniter..

If field 'title' belongs to table 'a',
field 'description' belongs to table 'b'
and field 'keywords' belongs to table 'c' then you can use like this :
$this->db->select('*');
$this->db->from('a, b, c');
$this->db->like(a.title, $search);
$this->db->or_like(b.description, $search);
$this->db->or_like(c.keywords, $search);
$query = $this->db->get();

Related

How to search for multiple keywords using sql search

I have a current SQL search query that lets users enter keywords to search for my SQL database. At the moment, the search will work with multiple words, but will show all results for either keyword. If you type in "Ford Mustang" it will show all results that have either "Ford" or "Mustang", but I need it to only show results that show both "Ford" and "Mustang".
What I have tried is below
public function getProductByName($name){
$stmt = $this->pdo->prepare('SELECT * FROM tbl_products WHERE name REGEXP :names');
$names = "[[:<:]](" . str_replace(" ", "|", $name) . ")[[:>:]]";
$stmt->execute(array('names' => $names));
return $stmt;
}
maybe this what you're looking for
select * from example where name like "%mustang%ford%"
You can write the query
select * from tbl_products where name like "%Mustang%" and name like "%ford%";
PHP code
//you may split search string like
$searchArray = explode(' ', $name);
//for loop for preparing the query
$query = 'SELECT * FROM tbl_products WHERE ';
$searchParams = array();
$conditions = [];
for($searchArray as $searchStr){
$conditions[] = 'name like ?';
$searchParams[] = "%$searchStr%";
}
//attach the conditions
$query .= implode(" and ", $conditions);
//execute the query
$stmt = $this->pdo->prepare($query);
$stmt->execute($searchParams);

How to properly check for keywords with MYSQL "LIKE"

I am wondering how I can properly check keywords with SQL "LIKE";
I have a script which looks like that:
$search_keywords = $_POST['search-keywords'];
$search_keywords = str_replace(" ","%", $search_keywords);
$search_keywords = '%' . $search_keywords . '%';
$search = $odb -> query("SELECT * FROM `cars` WHERE `keywords` LIKE '".$search_keywords."' ORDER BY `id` ASC");
$rows = $search->rowCount();
if ($rows > 0) {//Loop}
In fact, it's working but only when keywords in the database look like that:
audi, a3, silver and I search for audi a3
If i am trying to search like that: a3 audi it's not working
Any hints?
You need to split $search_keywords into separate words, and search for each of them.
To search for an item in a comma-separated list, use FIND_IN_SET() rather than LIKE. LIKE '%audi%' will also match audi-quatro.
$keyword_array = explode(" ", $_POST['search_keywords']);
foreach ($keyword_array as &$keyword) {
$keyword = "FIND_IN_SET('$keyword', keywords)";
}
$tests = implode(' AND ', $keyword_array);
// $tests contains something like: FIND_IN_SET('a3', keywords) AND FIND_IN_SET('audi', keywords)
$sql = "SELECT * FROM `cars` WHERE $tests ORDER BY `id` ASC";
$search = $odb->query($sql);
It's a best practice to use PDO::prepare when you are passing user data in your request, to evoid SQL Injection
$search = $odb->prepare("SELECT * FROM cars WHERE keywords
LIKE CONCAT('%',:keyword,'%')
ORDER BY id ASC");
$results = $search->execute([":keywork" => $search_keywords]);

php MySQL select priority

$query = "SELECT * FROM posts WHERE language='$lang' AND (title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')";
This does exactly what it should do. But what I'd like to do is having "title" as a priority. But as it looks now (every search is in a dropdown of html) it simple show's it without an priority. So the title can be at the very bottom, and the author at the top. Wrong order. I'd like to somehow always have the title at top.
How?
$output = '';
$lang = $_SESSION["lang"];
$search = $_POST["query"];
$query = "SELECT * FROM posts WHERE language='$lang' AND (title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')";
$result = mysqli_query($connect, $query);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$output .= '</ul>';
echo $output;
You can split up the query.
$output = '';
$lang = $_SESSION["lang"];
$search = $_POST["query"];
$query2 = "SELECT * FROM posts WHERE language='$lang' AND title LIKE '%$search%'";
$result2 = mysqli_query($connect, $query2);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result2) > 0)
{
while($row = mysqli_fetch_array($result2))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$query = "SELECT * FROM posts WHERE language='$lang' AND (author LIKE '%$search%' OR year LIKE '%$search%')";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$output .= '</ul>';
echo $output;
ORDER BY should do the trick for you here:
http://www.w3schools.com/sql/sql_orderby.asp
$query = "
SELECT book
, title
, url
FROM posts
WHERE language='$lang'
AND (
title LIKE '%$search%'
OR
author LIKE '%$search%'
OR
year LIKE '%$search%'
)
ORDER BY title ASC
, author ASC
, book ASC
";
I've added an optional order by 'author' and 'book' too (the priority of ordering starts with 'title', then 'author' and finally 'book') - you can change this to whatever you need though in ASC (ascending) or DESC (descending) order.
I'd also recommend you consider using bind params rather than passing in variables directly into your SQL to prevent SQL Injection.
Mysqli Bind Param Documentation
http://php.net/manual/en/mysqli-stmt.bind-param.php
Really good SO post here with help and more info about SQL Injection
How can I prevent SQL injection in PHP?
Also - try to avoid using SELECT * FROM... where possible, and only SELECT out the information you need. You'll be able to INDEX it better this way too (meaning quicker retrieval of data from the database).
You could use a scoring system to give each match a score and then sort by the match score. So a match for title gets a higher score and a match for author gets the next highest and so on. I'll rewrite just the query here:
SELECT *,
(
CASE
WHEN title LIKE '%$search%' THEN 100
WHEN author LIKE '%$search%' THEN 10
WHEN year LIKE '%$search%' THEN 1
END
) AS matchScore
FROM posts
WHERE
language='$lang' AND
(title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')
ORDER BY matchScore DESC

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%')

Dynamic while loop for MySql query

How would I shorten this mysql query for usage in php?
<?php
$sql = "SELECT * FROM $this->usernameid where
name LIKE '%$term%' OR
manufacture1 LIKE '%$term%' OR
manufacture2 LIKE '%$term%' OR
manufacture3 LIKE '%$term%' OR
manufacture4 LIKE '%$term%' OR
manufacture5 LIKE '%$term%' OR
manufacture6 LIKE '%$term%' OR
manufacture7 LIKE '%$term%' OR
manufacture8 LIKE '%$term%' OR
manufacture9 LIKE '%$term%' OR
manufacture10 LIKE '%$term%'
ORDER BY $order1";
?>
Looking to do a while loop, as an example here is my $_POST for another part of the program.
<?php
$i = 1;
while ($i < 10) {
$manufacture[$i] = strtoupper(filterinput($_POST['manufacture' . $i]));
$i++;
};
?>
// Base query
$baseQuery = "SELECT * FROM $this->usernameid WHERE name LIKE '%$term%' ";
// Get all columns from the table with manufacturers
$manufacturers = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA "
. "WHERE TABLE_NAME = '{YOUR_TABLE}' "
. "AND COLUMN_NAME LIKE 'manufacturer%';"
// Execute query
$getManufacturers = mysql_query( $manufacturers );
$addWhereClause = ''; // Additional WHERE clauses
// Loop over all the columns 'LIKE manufacturer%'
while ($manu = mysql_fetch_rows( $getManufacturers )) {
// Add an additional clause for every manufacturer
$addWhereClause .= "OR $manu LIKE '%$term% ";
}
// Append everything together and you have your dynamic query.
$query = $baseQuery.$addWhereClause."ORDER BY $order1;";

Categories