how to search fields on database with date range on mysql codeigniter - php

i've tried to create a search engine with date range filter but the whenever i type on my 'search_textbox' it does not include the date it only search the fields where it much the statement 'name' like '%a%';
if($search !=''):
$added_query = "and date_created like '%".$search."%' or
name like '%".$search."%' or
alias like '%".$search."%' or
designation like '%".$search."%'
";
else:
$added_query ="";
endif;
$project_details = $this->db->query("SELECT *
FROM ".$query."_man_power
WHERE date_created BETWEEN '".$date_from."' AND '".$date_to."'
".$added_query."
order by date_created desc
");
return $project_details;

You probably are not formatting the dates in your where clause properly. See:
https://www.w3schools.com/SQl/sql_dates.asp
You want to make sure $date_from and $date_to look like the following depending on type:
$date_from = '2018-06-01 0:00:00';
$date_to = '2018-06-30 23:59:59';
You can inspect your query better to find the problem by viewing it.
$sql = "SELECT * FROM ".$query."_man_power";
$sql .= " WHERE date_created BETWEEN '".$date_from."' AND '".$date_to."'".$added_query;
$sql .= " order by date_created desc";
var_dump($sql);
$project_details = $this->db->query($sql);

When combining these conditions, it is important to use parentheses so that the database knows what order to evaluate each condition.So group the AND,OR conditions with parenthesis like : -
if($search !=''):
$added_query = "and (
date_created like '%".$search."%' or
name like '%".$search."%' or
alias like '%".$search."%' or
designation like '%".$search."%'
)";
else:
$added_query ="";
endif;
$project_details = $this->db->query("SELECT *
FROM ".$query."_man_power
WHERE date_created BETWEEN '".$date_from."' AND '"
.$date_to."'".$added_query." order by date_created desc");
return $project_details;`

Related

Search condition using php,sql

I try to create search system using php and sql current condition is working fine but if I want
to search for John Doe (firstname + lastname) nothing happens. I try the + between firstname and lastname but it did not work.
Condition is here:
if(isset($_POST["query"])){
$search = mysqli_real_escape_string($conn, $_POST["query"]);
$query = "
SELECT * FROM users
WHERE firstname LIKE '%".$search."%'
OR lastname LIKE '%".$search."%'
";
}
You msy try something like this (using CONCAT):
$query = "SELECT * FROM users
WHERE firstname LIKE '%".$search."%'
OR lastname LIKE '%".$search."%'
OR CONCAT(firstname,' ', lastname) LIKE '%".$search."%'";

SQL query is overlooking a WHERE condition when filtering information from database

The following section of code is used to to filter data from an html page in real time from an SQL database using ajax. For some reason the condition in the SQL statement ignores the following condition samples_database.sample_storage != 'discarded' but it works in the second part of the else statement.
if(isset($_POST["query"])) {
$search = mysqli_real_escape_string($conn, $_POST["query"]);
$query .= "
SELECT * FROM samples_database JOIN storage_database on samples_database.storage_location=storage_database.id
WHERE samples_database.sample_storage != 'discarded'
AND samples_database.env_sam_id LIKE '%".$search."%'
OR samples_database.c_sam_id LIKE '%".$search."%'
OR samples_database.sample_type LIKE '%".$search."%'
OR storage_database.storage_name LIKE '%".$search."%'
ORDER BY samples_database.env_sam_id;";
} else {
$query .= "
SELECT * FROM samples_database JOIN storage_database on samples_database.storage_location=storage_database.id WHERE sample_storage != 'discarded' ORDER BY samples_database.env_sam_id;";
}
Can anybody help me this this silly problem please?
There's an order of precedence: AND is calculated before OR:
if(isset($_POST["query"])) {
$search = mysqli_real_escape_string($conn, $_POST["query"]);
$query .= "
SELECT * FROM samples_database JOIN storage_database on samples_database.storage_location=storage_database.id
WHERE samples_database.sample_storage != 'discarded'
AND (samples_database.env_sam_id LIKE '%".$search."%' OR
samples_database.c_sam_id LIKE '%".$search."%' OR
samples_database.sample_type LIKE '%".$search."%' OR
storage_database.storage_name LIKE '%".$search."%')
ORDER BY samples_database.env_sam_id;";
} else {
$query .= "
SELECT * FROM samples_database JOIN storage_database on samples_database.storage_location=storage_database.id WHERE sample_storage != 'discarded' ORDER BY samples_database.env_sam_id;";
}
In the else part you have only 1 condition:
sample_storage != 'discarded'
so it can't be "ignored".
But in the if part you have something like this:
A and B or C or D or E...
If one of C or D or E... is true then the result is true and you think that A is "ignored".
So make use of parentheses around each part that suits your needs.
maybe something like this:
A and (B or C or D or E...)

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

Query for If search value equals both rows?

I have this code pretty much like a search engine within the database for peoples names.
if (isset($_POST['submit'])){
$keyword = $_POST['stats'];
$orderby = $_POST['orderby'];
if (!empty($_POST['stats'])) {
$getStats = $db->query("SELECT * FROM `stats` WHERE
`lastname` LIKE '%$keyword%' OR `firstname` LIKE '%$keyword%' OR
`nickname` LIKE '%$keyword%' ORDER BY `$orderby`
DESC");
This then prints the results back into a table, I thought the table code wasn't necessary and too long.
The above query works for if I search just the last name or just the first name, or nickname
but if there is for example a user in the database with the name, John Smith
so
Firstname: John
Lastname: Smith
If just searched 'John' he would be printed into the table, which is good and same if I just searched 'Smith'
But if I search 'John Smith' he would not be printed into the table.
How can I change this query so that this will happen, I have tried this:
$getStats = $db->query("SELECT * FROM `stats` WHERE
`firstname`, `lastname` = '$keyword' OR `lastname` LIKE '%$keyword%' OR `firstname` LIKE '%$keyword%' OR
`nickname` LIKE '%$keyword%' ORDER BY `$orderby`
DESC");
WHERE CONCAT(firstname, ' ', lastname) LIKE %$keyword%
Also you should be binding parameters rather than directly interpolating user input into the query string, your current code is vulnerable to SQL injection.
$keyword = str_replace(" ", "%", $keyword);
You can try REGEXP:
$keyword = $db->real_escape_string($_POST['stats']); // escape data
$orderby = $db->real_escape_string($_POST['orderby']); // escape data
$keyword = implode("|", explode(" ", $keyword));
$getStats = $db->query("SELECT * FROM stats
WHERE firstname REGEXP '$keyword'
OR lastname REGEXP '$keyword'
OR nickname REGEXP '$keyword'
ORDER BY $orderby DESC");
try this
$sql = "SELECT *
FROM stats
WHERE
firstname LIKE '%$keyword%'
OR lastname LIKE '%$keyword%'
OR CONCAT_WS(' ',firstname,lastname,) LIKE '%$keyword%'
OR CONCAT_WS(' ',lastname,firstname) LIKE '%$keyword%'
OR nickname LIKE '%$keyword%'
ORDER BY $orderby DESC";

if argument inside mysql query

I have now three different PHP pages that contain almost the same information so to be able to reduce this to one page I need to have a php variable inside the mysql query.
Today it is like this:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";`
I need that the " AND Bruk = '1'" is removed from this query-line if i put ?nobruk=no in the adressbar. Is this possible and if so, how?
You don't want to (and can't) put an if inside your query; you want to use an if to create your query based on some condition. There are lots of ways to write this, one of which is
if (!empty($_GET['nobruk'])) {
$query1 = "SELECT ... WHERE `Kategori` = '1' ORDER BY ...";
}
else {
$query1 = "SELECT ... WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY ...";
}
Another way, which is shorter and involves the ternary operator, is
$includeBruk = empty($_GET['nobruk']);
$query1 = "SELECT ... WHERE `Kategori` = '1' ".
($includeBruk ? "AND `Bruk` = '1' " : "").
"ORDER BY ...";
A simple if statement:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1'";
if ($_GET['nobruk']!='no') {
$query1.=" AND `Bruk` = '1'";
}
$query1.= " ORDER BY yearstart DESC, mndstart DESC";
Like this :
<?php
$query = ($_REQUEST['nobruk'] == "no") ? "SELECT * FROM `Yrker` WHERE `Kategori` = '1' ORDER BY yearstart DESC, mndstart DESC": "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";
echo $query;
?>
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori`='1' ".($_GET['nobruk'] === 'no' ? "" : "AND `Bruk`='1' ")."ORDER BY yearstart DESC, mndstart DESC";

Categories