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);
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 have set up a query as such:
$query = 'SELECT SGC.sys_id, TBL.semester, SGC.bonus, SGC.exam, SGC.ca FROM SubjectGradeComponent AS SGC, ';
$query .= '(SELECT `sys_id`, `semester` FROM AcademicYearTerm AS AYT, SubjectYearTermLevel AS SYTL WHERE academic_year = "' . $academic_year . '" AND SYTL.subject_id = ' . $subject_id . ' AND SYTL.form_level = ' . $form_level. ' AND SYTL.yearTerm_id = AYT.yearTerm_id) AS TBL ';
$query .= 'WHERE SGC.sys_id = TBL.sys_id;';
However when I run the query, $mysql->query($query);it returns an empty result with 0 rows. Running the same query on phpmyadmin shows the desired result. I have looked around but do not understand the problem.
$mysql->error does not show any error message either
EDIT:
generated query is like this:
SELECT SGC.sys_id, TBL.semester, SGC.bonus, SGC.exam, SGC.ca FROM SubjectGradeComponent AS SGC, (SELECT `sys_id`, `semester` FROM AcademicYearTerm AS AYT, SubjectYearTermLevel AS SYTL WHERE academic_year = "2018-2019" AND SYTL.subject_id = 1 AND SYTL.form_level = 1 AND SYTL.yearTerm_id = AYT.yearTerm_id) AS TBL WHERE SGC.sys_id = TBL.sys_id;""
Question is where are the "" from?
Looks like you want a JOIN query instead.
You should also use prepared statement with placeholders ? instead of injecting values directly into the query.
$query = "SELECT SGC.sys_id,
AYT.semester,
SGC.bonus,
SGC.exam,
SGC.ca
FROM SubjectGradeComponent AS SGC
JOIN AcademicYearTerm AS AYT
ON SGC.sys_id = AYT.sys_id
JOIN SubjectYearTermLevel AS SYTL
ON SYTL.yearTerm_id = AYT.yearTerm_id
WHERE academic_year = ?
AND SYTL.subject_id = ?
AND SYTL.form_level = ?";
In the following example there is a base query. Other parameters can be dynamically added to complete the query.
However, my base query has no clause WHERE.
What is the best way to deal with it.
If I use in the base query, for example, WHERE 1 = 1, it seems to solve, but I have some doubts that is a correct solution.
$myQuery = "SELECT fr.oranges, fr.aplles, fr.bananas,
FROM fruits fr
LEFT JOIN countrys ct ON fr.id_fruit = ct.id_fruit";
if(!empty($countrys){
$myQuery .= " AND countrys = ? ";
}
if(!empty($sellers){
$myQuery .= " AND seller = ? ";
}
$myQuery .=" GROUP BY fr.id_fruit ORDER BY fr.fruit ASC";
Edited: I fixed a writing gap from $empty to empty.
The WHERE 1=1 is a simplistic hack that works well because it simplifies your code. There is a great post here which explains the performance implications of WHERE 1=1. The general consensus is it will have no effect on performance.
Also, slight note ($empty) is probably not a function you've defined. I think you want empty(). You could write it like this:
$myQuery = "SELECT fr.oranges, fr.aplles, fr.bananas,
FROM fruits fr
LEFT JOIN countrys ct ON fr.id_fruit = ct.id_fruit";
$where = [];
if(!empty($countrys){
$where[] = "countrys = ?";
}
if(!empty($sellers){
$where[] = "seller = ?";
}
if (!empty($where)) {
$myQuery .= " WHERE " . implode(" AND ", $where);
}
$myQuery .= " GROUP BY fr.id_fruit ORDER BY fr.fruit ASC";
You can use an array to control your SQL like this:
$where = [];
if(!$empty($countrys){
$where[] = " countrys = ? ";
}
if(!$empty($sellers){
$where[] = " seller = ? ";
}
if(count($where) > 0) {
$myQuery .= " WHERE ".implode('AND', $where);
}
I have this little issue with sql that doesn't function. I have a query which grows based on specific critera. Here it is
$SELECT = ' SELECT * ';
$FROM = ' FROM a ';
$WHERE = ' WHERE TRUE ';
$how = ' GROUP By a_id ';
$result = mysqli_query($link, $SELECT . $FROM . $WHERE . $how );
This works but the second stage doesn't
$FROM .= " INNER JOIN b ON b_aid = a_id";
$WHERE .= " AND b_id = $id";
Specifically, the additional $WHERE . causes an undefined variable. If it is removed, I can see within the array the line I am after.
The normal query $result = mysqli_query($link, $SQL) works ok for the above;
Thanks
So I have to add a WHERE query to this plugin I'm using for a reporting feature on a WordPress site. I have no time to do anything but add in another column and filter by the values in that column as there is not that much data to manage each update. The default value for the column I added is zero but I'll add new entries to represent years new people are added. However, when I filter based on the column value the whole query breaks and doesn't show up. I have no idea why. Here is the section involving its set up query displaying results.
<?php
$sql = "SELECT COUNT(*) FROM " . $wpdb->prefix . "presidentsreport_breakdown WHERE list_id = " . $atts['list_id'];
$total_breakdowns = $wpdb->get_var($sql);
$sql = "SELECT p.person_id, p.name, p.notes, p.school_year, b.breakdown_id, b.name as breakdown, b.description as breakdown_description FROM " . $wpdb->prefix . "presidentsreport_person p INNER JOIN " . $wpdb->prefix . "presidentsreport_breakdown b ON b.breakdown_id = p.breakdown_id INNER JOIN " . $wpdb->prefix . "presidentsreport_list l ON l.list_id = b.list_id";
$clean_where = " WHERE l.list_id = " . $atts['list_id'];
$where = "";
if($search != ''){
$where = " AND (p.name LIKE %s)";
$arg = '%' . $search . '%';
$args = array($arg);
}
$where = $wpdb->prepare($where, $args);
$order = " ORDER BY b.sort_order, b.breakdown_id, p.sort_name, p.name, p.person_id";
$results = $wpdb->get_results($sql . $clean_where . $where . $order);
?>
If I add anything in the variable $where it breaks the whole query. So if I add
<?php
$where = " WHERE p.school_year <= 2011";
?>
or
<?php
$where = " WHERE p.school_year = 0";
?>
Nothing will show up, For the last example if the default value is 0 everything should show up regardless. Thanks in advance for reading through!
Don't add WHERE to your variable. It is already assigned in $clean_where
$clean_where = " WHERE l.list_id = " . $atts['list_id'];
Here ------------^
You need to concatenate your addition parameters to the $where variable:
$where .= " AND p.school_year <= 2011";
There's no need of WHERE in where!