SQL select, from, where, how - php

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

Related

php mysql query adds quotes in the end

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

SQL Statement: Getting results based on 2 values

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

Query Structure: SELECT FROM places WHERE Type = 1

Okay so i am trying to display all entries in one of my database tables where the field 'Type' has a value of 1 but i keep getting an error. I'm not sure how to structure my query.
<?php
include 'page-start.php';
?>
<?php
$myQuery = "SELECT places.*, Type.TypeName ";
$myQuery .= "FROM places ";
$myQuery .= "WHERE Type = '1' ";
$myQuery .= "INNER JOIN Type ON places.Type = Type.TypeID";
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));
?>
<?php
while($row = mysqli_fetch_array($result))
{
echo ' <div class="one-third column" id="education">';
echo '<h3 class="place-head">' . $row['PlaceName'] . '</h3>';
echo ' <div class="a-image">';
echo '<img src="'. $row['ImageURL'] . '"/>';
echo ' </div>';
echo ' <div class="a-info">';
echo ' </div>';
echo '</div>';
}
?>
After playing around i managed to get it working by executing the query on its own underneath the first query like this:
<?php
$myQuery = "SELECT places.*, Type.TypeName ";
$myQuery .= "FROM places ";
$myQuery .= "INNER JOIN Type ON places.TypeID = Type.TypeID";
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));
?>
<?php
$myQuery = "SELECT * FROM `places` WHERE `TypeID` = '1'";
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));
?>
I don't know if this was the correct way of getting round my problem but it works. Thanks for the help anyway guys.
I believe you have an SQL syntax error?
$myQuery = "SELECT places.*, Type.TypeName ";
$myQuery .= "FROM places ";
$myQuery .= "WHERE Type = '1' ";
$myQuery .= "INNER JOIN Type ON places.Type = Type.TypeID";
The inner join should precede your predicate ("WHERE Type = '1'"):
$myQuery = "SELECT places.*, Type.TypeName ";
$myQuery .= "FROM places ";
$myQuery .= "INNER JOIN Type ON places.Type = Type.TypeID";
$myQuery .= "WHERE Type = '1' ";
Don't pass $result to mysqli_error, that's not what it wants, it wants your $con variable passed in as the parameter.
Also, since you're using the mysqli object, just call $con->error to print the error message.
And since you're returning a mysqli_result objects, you should probably just use
while ($row = $result->fetch_array(MYSQLI_ASSOC) )
as your while loop command.

Entering my WHERE into the query breaks it

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!

PHP query does not return result

This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"

Categories