$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
Related
I have two text boxes keywords and location. when i search with keywords AND location it gives me the result but when i search only with location it does not.
$keywords = isset($_POST['keywords']) ? $_POST['keywords']:'';
$location = isset($_POST['location']) ? $_POST['location']:'';
if (isset($keywords)){
$search = "SELECT * FROM table1
WHERE table1 .field1 LIKE :keyword OR table1 .field2 LIKE :keyword ";
if(isset($location)){
$search .= "AND table1 .field5 LIKE :location";
}
}else if(isset($location)){
$search ="SELECT * FROM table1
WHERE jtable1 .field5 LIKE :location";
}
$keywords="%".$keywords."%";
$location="%".$location."%";
$statement = $connection->prepare($search);
$statement->execute(array(
':keyword'=> $keywords,
':location'=>$location
));
$result = $statement->fetchAll();
The first if stmt works but when when i search by location only, it gives me all the result but i just want to give result by that location.
$query = "SELECT * FROM tbl_country WHERE language='$lang' AND country_name LIKE '%".$_POST["query"]."%' OR country_second LIKE '%".$_POST["query"]."%'";
The above will not work. I want it to search in 2 fields (works) but based of the language I've set. But it simply skips the lang part
Try this
$search = $_POST["query"];
if(empty($search))
{
echo "Search filed is empty";
}
elseif (empty($lang)) {
echo "Lang filed is empty";
}
else
{
$query = "SELECT * FROM tbl_country WHERE language='$lang' AND
(country_name LIKE '%$search%' OR country_second LIKE '%$search%') ";
}
Wrap with ()
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();
The following code works well, but I couldn't find a way to limit the number of results. Any ideas please?
$q = "some keywords for search"; // always escape
$keys = explode( " ",$q );
$query = "SELECT * FROM table WHERE para LIKE '%$q%' ";
foreach($keys as $k)
{
$query .= " OR para LIKE '%$k%'";
}
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc())
{
if ($row != 0) {
$title = $row['title'];
}
}
Any help while be appreciated.
Note: the $q holds the search keywords, and then the code explode it, and search for the keywords in 2 steps:
1- as one sentence using ($q as it is).
2- it searches for each keyword as an array after exploding the $q (here is the part that the "foreach" does).
After that the code loops using "while" to find all results match the search request.
Use LIMIT after completing your query.
Also, if you want to get results sorted by some fields in your table, you could also say " ORDER BY fieldname ASC|DESC"
As follows:
$q = "some keywords for search"; // always escape
$keys = explode( " ",$q );
$query = "SELECT * FROM table WHERE para LIKE '%$q%' ";
foreach($keys as $k)
{
$query .= " OR para LIKE '%$k%'";
}
$query .= " LIMIT 10"; //<<<<<<<<<<<<<<<
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc())
{
if ($row != 0) {
$title = $row['title'];
}
Use LIMIT.
SELECT * FROM table WHERE para LIKE '%$q%' LIMIT 2
You can limit the number of results in your MySQL query, like so:
$query = "SELECT * FROM table WHERE para LIKE '%$q%' LIMIT 5";
this will limit it to 5 results. If you want 10, change it to 10
I am using LIKE to do my searching, i try it in phpMyAdmin and return the result but when i use it in php it return empty result.
$search = "ip";
$start = 0;
$query = "SELECT * FROM product WHERE product_name LIKE '%$search%' LIMIT $start,30";
$result = mysql_query($query);
if(empty($result))
$nrows = 0;
else
$nrows = mysql_num_rows($result);
It will return result when i using phpMyAdmin to run this query but when i use it in php, it return empty.
Update:
Sorry guys,
I just found out the problem is i didn't connect database as well. anyway, thanks for helping.
Try This
$query = "SELECT * FROM `product` WHERE `product_name` LIKE '%".$search."%' LIMIT 0, 30";
And if the sole purpose of your code is to get the number of products with the searched-for name, use SELECT COUNT(*) instead of doing a mysql_num_rows() on all your data. It will decrease your querytime and the amount of data that is (unnecessarily) fetched.
I am not sure why this is not working, as the query seems to be correct to me. I would like to suggest you writing query this way
$query = <<<SQL
SELECT * FROM product WHERE product_name LIKE "%$search%" LIMIT $start,30
SQL;
please note that there should not be any space or any character after SQL;
$query = "SELECT * FROM product WHERE product_name LIKE '%" . $search . "%' LIMIT " . (int) $start. ",30";
you can use directly mysql_num_rows()
but here is right code
$query = "SELECT * FROM product WHERE product_name LIKE '%".$search."%' LIMIT $start,30";
$search = "ip";
$start = '0';
$query = "SELECT * FROM product WHERE product_name LIKE '%".$search."%' LIMIT $start,30";
$result = mysql_query($query)or die(mysql_error());
if(mysql_num_rows($result) == 0){
$nrows = 0;
} else{
$nrows = mysql_num_rows($result);
}
//use mysql_num_rows($result) instead of empty($result) because in this situation $result is every time not empty so use inbuilt PHP function mysql_num_rows($result);