I can search multiple value with mysql.
I need to implement SORT BY on it
This is my coding which is working perfect
$conditions = array();
if ($key) {
$conditions[] = 'job_title LIKE "%'.$key.'%"';
}
if ($category) {
$conditions[] = 'job_category = "'.$category.'"';
}
if ($location) {
$conditions[] = 'job_location = "'.$location.'"';
}
if ($country) {
$conditions[] = 'job_country = "'.$country.'"';
}
if ($salary) {
$conditions[] = 'job_salary >= "'.$salary.'"';
}
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id '.implode(' AND ', $conditions);
When I apply SORT BY
like this
if ($sort)
{
$conditions[] = 'ORDER BY "'.$sort.'"';
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id '.implode(' AND ', $conditions);
}
else
{
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id '.implode(' AND ', $conditions);
}
result is
Blockquote
SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id job_location = "Manjeri" AND ORDER BY "job_salary"
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/work/mobjob/test.php on line 41
you shouldn't implode your order by as a condition.. it's not one..
just append it onto the end like so:
$sqlStatement = 'SELECT * FROM jobs JOIN job_category ON jobs.job_category=job_category.category_id ';
if( sizeof($conditions)) {
$sqlStatement .= ' WHERE ' . implode(' AND ', $conditions);
}
if($sort) {
$sqlStatement .= ' ORDER BY "'.$sort.'"';
}
Related
I have a database filled with addresses. 6 columns (id, Name, Address, City, State, Zip, dt)
My code is run with ajax for live search. Currently I can mostly find what I'm looking for with my queries. The problem I'm running into is this. If I search for "90210 Steve Jones" I get no results but if I search for "Steve Jones 90210" it finds the row(s).
Here is my code:
$query = "SELECT * FROM db";
if($_POST['query'] != '')
{
$postq = mysql_real_escape_string($_POST['query']);
$query .= "WHERE CONCAT(Name,Address,City,State,Zip) LIKE '%".str_replace(' ', '%', $postq)."%'";
}
$query .= 'ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
$statement->execute();
Any help would be appreciated
One of the solutions is to split the search string by spaces and then do a multiple like comparison operations
So the code is:
<?php
if($_POST['query'] != '') {
$postq = mysql_real_escape_string($_POST['query']);
$pieces = explode(" ", $postq);
$index=0;
$substring="";
while ($index < count($pieces)) {
$substring .=" CONCAT(Name,Address,City,State,Zip) like '%" . $pieces[$index] . "%'" ;
if ($index !=count($pieces)-1){
$substring .= " and ";
}
$index++;
}
$query = "SELECT * FROM db where ";
$query .= $substring;
$query .= ' ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
$statement->execute();
}
?>
You could break up your query by spaces and test for each.
$query = "SELECT * FROM db";
$where = [];
$values = [];
$ss = [];
if($_POST['query'] != '')
{
foreach( explode(' ', $_POST['query']) as $p) {
$postq = mysql_real_escape_string($p);
$where[]= "(CONCAT(Name,Address,City,State,Zip) LIKE ? )";
$values[] = "%$postq%";
$ss[]='s';
}
$query .= " WHERE " . implode(" OR ", $where);
}
$query .= ' ORDER BY Name ASC, dt DESC ';
$statement = $connect->prepare($query);
if(count($values)>0) $statement->bind_param(implode('',$ss), ...$values);
$statement->execute();
I've got a pretty complex SQL statement and want to add a WHERE clause that only selects results WHERE the hidden column IS NOT '1', however it needs to relate to a specific user.
i.e If in table 1 hidden is 1 and userid is 1 I don't want to get this results. However as there is no record for user 2 in that table I want them to see it.
This is what I have managed to get working so far:
$where .= " AND uh.hidden IS NULL ";
However if I login as User 2 then I see the same results as user 1.
How do I make it so results are shown based on the user too?
SQL query:
$pdo = new PDO('mysql:host=localhost;dbname=myDB', 'root', 'root');
$select = 'SELECT tl.id,
tl.name,
tl.locale,
ROUND(AVG(pr.rating),0) AS rating ';
$from = ' FROM theList AS tl ';
$join = ' LEFT JOIN post_rating AS pr ON tl.id = pr.postid ';
$join2 = ' LEFT JOIN user_hidden_list AS uh ON uh.est_id = tl.id ';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : [''];
$where = ' WHERE 1 = 1 ';
if (in_array("pub", $opts)) {
$where .= " AND pub = 1";
}
if (in_array("bar", $opts)) {
$where .= " AND bar = 1";
}
$where = ' WHERE uh.hidden IS NULL ';
$group = ' GROUP BY tl.id, tl.name ';
$sql = $select . $from . $join . $join2 . $where . $group;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
I tried to build a dynamic query, but I faced an error telling me that the parameter count is inappropriate everything seems to be ok for me there are 4 params.
My attempt
$activeFilters
array(1) {
["zlec_addres"]=>
string(2) "Sz"
["zlec_nr"]=>
string(3) "OPC"
}
function cond_gen(array $activeFilters)
{
$query_var = [];
$i=0;
foreach ($activeFilters as $key => $value) {
$query_var[] = '`'.array_keys($activeFilters)[$i].'` LIKE concat("%",:condition'.$i.',"%")';
$i++;
}
return 'WHERE ' . implode('AND', $query_var);
}
$conditions = cond_gen($activeFilters);
//eqb
$db->bindMore($activeFilters);
$db->bind("start",$start);
$db->bind("pagesize",$pagesize);
$dynQuery = $db->query("SELECT zlec_status.nazwa AS Status,
piorytet.nazwa AS Priorytet,
Concat(koord.imie, ' ', koord.nazwisko) AS `Koordynator`,
Concat(zlec_adresy.miasto, ' - ', zlec_adresy.ulica, ' ',
zlec_adresy.oddzial)
AS `adres`,
zlec_z_dnia,zlec_id,
zlec_nr,
zlec_do,
zlec_ogran,
awizacje,
awizacja_na_dzien,
termin_zamkniecia,
tresc,
uwagi
FROM zlec
INNER JOIN koord
ON zlec.koord = koord.id
INNER JOIN zlec_adresy
ON zlec.zlec_addres = zlec_adresy.id
INNER JOIN piorytet
ON zlec.priorytet = piorytet.id
INNER JOIN zlec_status
ON zlec.status_zlecenia = zlec_status.id
$conditions
LIMIT :start, :pagesize");
SQL Error Unhandled Exception. SQLSTATE[HY093]: Invalid parameter number
WHERE `zlec_addres` LIKE concat("%",:condition0,"%")AND`zlec_nr` LIKE concat("%",:condition1,"%")
LIMIT :start, :pagesize
Working code for me
function cond_gen(array $activeFilters)
{
$query_var = [];
$i=0;
foreach ($activeFilters as $key => $value) {
$query_var[] = '`'.array_keys($activeFilters)[$i].'` LIKE concat(\'%\',:'.array_keys($activeFilters)[$i].',\'%\')';
$i++;
}
return 'WHERE ' . implode(' AND ', $query_var);
}
$conditions = cond_gen($activeFilters);
echo cond_gen($activeFilters);
//eqb
var_dump($activeFilters);
$db->bindMore($activeFilters);
$db->bind("start",$start);
$db->bind("pagesize",$pagesize);
$dynQuery = $db->query("SELECT zlec_status.nazwa AS Status,
piorytet.nazwa AS Priorytet,
Concat(koord.imie, ' ', koord.nazwisko) AS `Koordynator`,
Concat(zlec_adresy.miasto, ' - ', zlec_adresy.ulica, ' ',
zlec_adresy.oddzial)
AS `adres`,
zlec_z_dnia,zlec_id,
zlec_nr,
zlec_do,
zlec_ogran,
awizacje,
awizacja_na_dzien,
termin_zamkniecia,
tresc,
uwagi
FROM zlec
INNER JOIN koord
ON zlec.koord = koord.id
INNER JOIN zlec_adresy
ON zlec.zlec_addres = zlec_adresy.id
INNER JOIN piorytet
ON zlec.priorytet = piorytet.id
INNER JOIN zlec_status
ON zlec.status_zlecenia = zlec_status.id
$conditions
LIMIT :start, :pagesize");
I have a pdo command like this $sql = $pdoObj->execute($query) but it does not work, 0 result returning. I echo'ed out the $query variable just before calling execute() and then pasted it inside the execute() and the code ran successfully. I can't understand what is the problem here as I have done this in other parts of my code without problems.
Here are some examples of the queries:
SELECT s.id, s.marca, s.colore, s.prezzo, i.id_scarpa, i.taglia FROM scarpe AS s INNER JOIN info_scarpe AS i ON i.id_scarpa = s.id WHERE 1 = 1 AND taglia IN ('40','41','42') AND colore IN ('rosso', 'nero')
SELECT * FROM scarpe WHERE 1=1
SELECT * FROM scarpe WHERE 1=1 AND marca IN ('adidas','nike')
They are all dynamic generated queries based on the $_GET variable.
EDIT:
Sure
if ( isset($_GET) ) {
if ( isset($_GET['taglia']) ) {
$query = "
SELECT
s.id, s.marca, s.colore, s.prezzo, i.id_scarpa, i.taglia
FROM
scarpe AS s
INNER JOIN
info_scarpe AS i
ON i.id_scarpa = s.id
WHERE
1 = 1
";
foreach ( $_GET as $index => $val ) {
$a = explode(',', $val);
$in = "'" . implode("','", $a) . "'";
$query .= ' AND '.$index.' IN ('.$in.')';
}
} else {
$query = " SELECT * FROM scarpe WHERE 1=1";
foreach ( $_GET as $index => $val ) {
$a = explode(',', $val);
$in = "'" . implode("','", $a) . "'";
$query .= ' AND '.$index.' IN ('.$in.')';
}
}
echo 'data loaded';
} else {
$query = " SELECT * FROM scarpe ORDER BY id DESC ";
}
EDIT2:
I use query() and not execute() but still does not work
The arguments for execute should be an array with query parameters. You mean to use either
$result = $pdoObj->query($query);
OR
$stmt = $pdoObj->prepare($query);
$stmt->execute();
I have two variables in my WHERE statement. I cant seem to separate them with a space so i end up getting a syntax error. Thanks for the help.
(I am using codeigniter)
btw i have tried setting a $space variable, and putting spaces before the and, after setting both variables, and in the sql.
ERROR
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'source_adusers.ad_account="Wolfs, Marc" GROUP BY rollout_systems.eam_user LIMIT ' at line 2
SELECT *, COUNT(rollout_systems.EAM_USER) as systems FROM rollout_systems LEFT JOIN source_adusers ON rollout_systems.EAM_User = source_adusers.ad_account WHERE rollout_systems.scope_ID = 3AND source_adusers.ad_account="Wolfs, Marc" GROUP BY rollout_systems.eam_user LIMIT 0,50
Line Number: 330
PHP
if ($this->session->userdata('scopeId') != NULL) {
$where1 = 'WHERE rollout_systems.scope_ID = '. $this->session->userdata('scopeId') . '';
} else {
redirect('/headquarters/home');;
}
if ($search) {
$where2 = ' AND rollout_systems.sys_name ="'.$search.'"';
} else {
$where2 = '';
}
$query = $this->db->query('SELECT * FROM rollout_systems LEFT JOIN source_adusers
ON rollout_systems.eam_user = source_adusers.ad_account '. $where1 .''. $where2 .' GROUP BY rollout_systems.sys_name LIMIT '.$limit.',50');
what if you keep the spaces and the AND in the $query, instead of building them into your where variables? Then your $where 2 just needs to work without affecting the query - thus 0=0.
if ($this->session->userdata('scopeId') != NULL) {
$where1 = 'WHERE rollout_systems.scope_ID = '. $this->session->userdata('scopeId') . '';
} else {
redirect('/headquarters/home');;
}
if ($search) {
$where2 = 'rollout_systems.sys_name ="'.$search.'"';
} else {
$where2 = '0=0';
}
$query = $this->db->query('SELECT * FROM rollout_systems LEFT JOIN source_adusers
ON rollout_systems.eam_user = source_adusers.ad_account '. $where1 .' and '. $where2 .' GROUP BY rollout_systems.sys_name LIMIT '.$limit.',50');
Just add a space between the two vars - '. $where1 .' '. $where2 .'
As pointed out by others you really should be escaping your user input using mysql_real_escape_string() or intval() if you are expecting an integer value. If you are using PDO or mysqli use prepared statements.
If $this->db is a PDO instance you could use -
$params = array();
if ($this->session->userdata('scopeId') != NULL) {
$where = 'WHERE rollout_systems.scope_ID = ?';
$params[] = $this->session->userdata('scopeId');
} else {
redirect('/headquarters/home');;
}
if ($search) {
$where .= ' AND rollout_systems.sys_name = ?';
$params[] = $search;
}
$sql = "SELECT * FROM rollout_systems
LEFT JOIN source_adusers ON rollout_systems.eam_user = source_adusers.ad_account
$where
GROUP BY rollout_systems.sys_name
LIMIT ?, 50";
$params[] = $limit;
$query = $this->db->prepare($sql);
$query->execute($params);
$where = array();
if ($this->session->userdata('scopeId') != NULL) {
// better to escape your parameter here unless you trust it totally
// judging by its name, it's user-provided data, so I wouldn't trust it
$where[] = 'rollout_systems.scope_ID = '. $this->session->userdata('scopeId');
} else {
redirect('/headquarters/home');
// you may need to exit here after redirection, depends on your implementation
}
if ($search) {
// once again don't forget to escape $search in real application
$where[] = "rollout_systems.sys_name = '" . $search . "'";
}
$query = $this->db->query("
SELECT
*
FROM
`rollout_systems`
LEFT JOIN
`source_adusers`
ON rollout_systems.eam_user = source_adusers.ad_account
WHERE
" . implode (' AND ', $where) . "
GROUP BY
rollout_systems.sys_name
LIMIT " . $limit /* escape it! */ . ",50"
);
You also have the option to use the PHP syntax
$sql = " blah blah {$my_var} {$my_other_var} ";