Dynamic while loop for MySql query - php

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;";

Related

advanced search not giving me the result when it reaches the else if stmt

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.

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

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;`

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

Codeigniter auto-update search with %LIKE%

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();

query works on MySQL, but no in PHP, why?

I need to display the results of this query :
SELECT * FROM projects WHERE PrestaCmd LIKE '% A - CREP - DPE - %'
but in PHP, this query doesn't work :s
This is my code :
$req = "SELECT * FROM ".$table." WHERE PrestaCmd LIKE '%".$ch."%'";
echo $req; //returns : SELECT * FROM jos_projectlog_projects WHERE PrestaCmd LIKE '% A - CREP - DPE - %'
$results = mysql_query($req);
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
print_r($row);
}
I think the problem is coming from the '$ch' variable.
But when I put an echo of the query, it's correct, and when I put a query like this :
$req = "SELECT * FROM jos_projectlog_projects WHERE PrestaCmd LIKE '% A - CREP - DPE - %'";
echo $req;
$results = mysql_query($req);
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
print_r($row);
}
it works :s
#Bahumat100, if you think you have   to make space which is causing problem, then use html_entity_decode and do it like this:
$req = "SELECT * FROM ".$table." WHERE PrestaCmd LIKE '%".html_entity_decode($ch)."%'";

Categories