orderfood
orderfood_id food_id total_amount
foodcancel
foodcancel_id food_id status
$query = $this->db->query("SELECT * FROM order_food of LEFT JOIN `foodcancel` fc ON of.food_id = fc.food_id WHERE of.orderfood_id = '" . (int)$orderfood_id . "'");
$order_foods = $query->rows;
above is my query, what i wanted is that if there food_id inside foodcancel table , exclude it from rows, possbile to do it ?
For exclude the existing values you could try checking null for corresponding matching value
SELECT *
FROM order_food of
LEFT JOIN foodcancel fc ON of.food_id = fc.food_id
and of.food_id = your_value
WHERE fc.orderfood_id is null
anyway you should not php var in your sql code because in this way you are are risk for sqlinjection for avoid this you should take a look at prepared statement and binding param
It's very possible to do. In my logic. first, you must get all food_id on food_cancel table. Then save it into variabel and use it when you show orderFood table with adding NOT IN condition.
I've write code for you,
<?php
// Get Food Id From Cancel
$orderCancel = mysqli_query($mysqli, "SELECT * FROM `foodcancel`");
$cancelId = "";
while ($cancel = mysqli_fetch_array($orderCancel)) {
$cancelId .= $cancel["food_id"].",";
};
$cancelId = substr($cancelId, 0, -1);
// Put Food Id on Cancel Table into NOT IN Condition Database
$orderFood = mysqli_query($mysqli, "SELECT * FROM `orderfood` WHERE food_id NOT IN ($cancelId)");
while ($order = mysqli_fetch_assoc($orderFood)) {
$food[] = $order;
};
echo json_encode($food);
?>
Related
I am having problems achieving the query to select data from a table in the db after a defined value has been met.
My code to do this is:
$fi = 'first_segment'
$im = popo.jpg
$sqls = "SELECT * FROM $fi,news_pictures
WHERE $fi.pi_id = news_pictures.pi_id
AND news_pictures.i_name = '$im'
GROUP BY news_pictures.id DESC";
I wasn't able to achieve the result with that query.
Basically, I want the query to confirm if news_pictures.i_name = '$im' and if true, return starts from the value of $im followed by other data in the table depending on news_pictures.id DESC.
The sample data and output:
Table news_pictures:
id i_name
-- ------
1 coco.jpg
2 lolo.jpg
3 popo.jpg
4 dodo.jpg
Since $im = popo.jpg, I want my query to display all values starting from popo.jpg with id DESC, i.e. popo.jpg, lolo.jpg, coco.jpg.
I got to solve the question with the help of a friend.
$fsqls = "SELECT * FROM $fi,news_pictures WHERE $fi.pi_id = news_pictures.pi_id AND news_pictures.i_name = '$im' GROUP BY news_pictures.id";
$rres = mysqli_query($connection, $fsqls) or print(mysqli_error($connection));
while($row = mysqli_fetch_assoc($rres))
{
$rnm = $row["id"];
}
$sqls = "SELECT * FROM news_pictures WHERE news_pictures.id <= $rnm ORDER BY news_pictures.id DESC";
I have a nested while statement that gives the results I need but is very inefficient and takes forever to run? Any thoughts on how these could be combined?
I first create a temporary table with all the data I need from a larger table called student grades. I then get the students and course names because I want to group these for each report. I then look for each student then get the scores for each assignment. I also want to get the average of the only of the last three assignments for each particular learning outcome ID.
//MYSQL query to create temp table
$qryTmp = "CREATE TEMPORARY TABLE IF NOT EXISTS tmp AS (SELECT studentsisid,coursename,assessmenttitle,studentname,outcomescore,recordid,learningoutcomeid,learningoutcomename,assessmentid
from studentgrades
WHERE studentsisid LIKE '$studentid' AND coursename LIKE '$coursename')";
mysql_query($qryTmp);
//MYSQL query Coursename and student name
$qryCourse = "SELECT studentsisid,coursename,studentname
from tmp
WHERE studentsisid LIKE '$studentid' AND coursename LIKE '$coursename' GROUP BY studentsisid,coursename ORDER by studentname,coursename";
$resultCourse=mysql_query($qryCourse);
while ($rowCourse = mysql_fetch_assoc($resultCourse)) {
$studentid = $rowCourse['studentsisid'];
$name = $rowCourse['studentname'];
$coursename = $rowCourse['coursename'];
//MYSQL query Learning Outcome ID
$qryLID ="SELECT outcomescore,learningoutcomeid,count(RecordID) as assessmentcount
from tmp
WHERE studentsisid = '$studentid' AND coursename='$coursename'
Group by studentsisid,coursename, learningoutcomeid ORDER BY studentname, coursename";
$resultLID=mysql_query($qryLID);
while ($rowLID = mysql_fetch_assoc($resultLID)) {
$learningoutcomeid = (int)$rowLID['learningoutcomeid'];
$assessmentcount = (int)$rowLID['assessmentcount'];
//MYSQL query recent 3
$qryRecent3 = "SELECT avg(outcomescore) as recentscoreavg
FROM
(SELECT outcomescore FROM tmp WHERE
studentsisid='$studentid' AND coursename='$coursename' AND learningoutcomeid='$learningoutcomeid'
ORDER BY AssessmentID DESC LIMIT 3) as r";
$resultRecent3=mysql_query($qryRecent3);
while ($rowRecent3 = mysql_fetch_assoc($resultRecent3)) {
$recentscoreavg = number_format($rowRecent3['recentscoreavg'], 1);
$assessmentcount = $rowRecent3['recentover3'];
}
}
}
I have two different sql statements. $sql grabs all the items whose title matches a certain search text. $cat_sql grabs all the category_items that are in a certain category. An item has an ID. A category_item has a field called item_id which is a foreign key to IDs in the items table
...
mysqli setup code
...
$title = $_POST["title"];
$cat_id = $_POST["cat_id"];
$cat_sql = "SELECT * FROM category_items WHERE category_id = '".$cat_id."'";
$sql = "SELECT * FROM items where title LIKE '%". $title ."%' Limit 70";
if (!$result_cat = $mysqli->query($cat_sql)) {
// The query failed.
echo "<h2 >ERROR</h2>";
exit;
}
if (!$result = $mysqli->query($sql)) {
// The query failed.
echo "<h2 >ERROR</h2>";
exit;
}
Then I display all items:
while ($item = $result->fetch_assoc()) {
include 'item_card.php';
}
Currently this just displays all items fetched in the $sql query. Is there some way to remove all items from $result that do not have their ID represented as an item_id in $result_cat?
NOTE:
I would strongly prefer not to do just combine both SELECT statements into a table join because the actual $sql and $cat_sql are not nearly as simple as I have represented here. Also, they vary depending on which if statement they are in.
My question is: given $result and $result_cat, can I remove items from $result?
EDIT 1
As suggested by comments I am making an array if item_ids then doing an in_array query. Progress thus far:
$result_cat_ids = [];
while ($cat_item = $result_cat->fetch_assoc()) {
$result_cat_ids[] = $cat_item['item_id'];
}
EDIT 2 Here is the working code following the suggestions in the comments
if (in_array($item['id'], $result_cat_ids)) {
include 'item_card.php';
}
You may also use 'INTERSECT' sql clause.
$sql = "SELECT * FROM items WHERE id IN (SELECT item_id FROM category_items WHERE category_id = '".$cat_id."' INTERSECT SELECT id FROM items where title LIKE '%". $title ."%')";
This way, you can query for items that accomplish both conditions.
Note: I'm not using "limit 70" but you may add it as well.
So I am trying to use a result from an SQL search $search_course and then having that as the WHERE LIKE part of the next statement $Search_Module.
once the $Search_Module query has finished I would like the results to be in a list which I know should be coded correctly.
I have tried the following code but the search returns no values;
Any help with this would be much appreciated, thanks in advance.
$search_course = "
SELECT title, id, wyl, overview, module, course, careers
FROM course
LEFT JOIN cm
ON course.id=cm.course
WHERE id LIKE '%".$_POST['submitcourseselection']."%'";
$result = $mysqli->query($search_course) or die($mysqli->error);
$display_course = $result->fetch_assoc();
//Searches the module table in the DB for modules within the course
$Search_Module = "
SELECT id, title, level, credits
FROM module
WHERE id LIKE '".$search_course['module']."'";
$M_Results = $mysqli->query($Search_Module) or die($mysqli->error);
$ModuleList = '';
while ($MResults = $M_Results->fetch_assoc()) {
$ID = $MResults['id'];
$Title = $MResults['title'];
$Level = $MResults['level'];
$Credits = $MResults['credits'];
$ModuleList.='<div><h2>'.$Title.'</h2></div>';
}
you don't need LIKE in your second query and you can do all by one query.
$search_course = "
SELECT id, title, level, credits
FROM module
WHERE id IN (SELECT module
FROM course
LEFT JOIN cm
ON course.id=cm.course
WHERE id LIKE '%".$_POST['submitcourseselection']."%'")";
in your where clause WHERE id LIKE '".$search_course['module']."'";, you are referencing an array location of a string $search_course, which is your SQL statement.
I think you meant to reference your result array $display_course, so try this:
$search_course = "
SELECT title, id, wyl, overview, module, course, careers
FROM course
LEFT JOIN cm
ON course.id=cm.course
WHERE id LIKE '%".$_POST['submitcourseselection']."%'";
$result = $mysqli->query($search_course) or die($mysqli->error);
$display_course = $result->fetch_assoc();
//Searches the module table in the DB for modules within the course
$Search_Module = "
SELECT id, title, level, credits
FROM module
WHERE id LIKE '".$display_course['module']."'";
$M_Results = $mysqli->query($Search_Module) or die($mysqli->error);
$ModuleList = '';
while ($MResults = $M_Results->fetch_assoc()) {
$ID = $MResults['id'];
$Title = $MResults['title'];
$Level = $MResults['level'];
$Credits = $MResults['credits'];
$ModuleList.='<div><h2>'.$Title.'</h2></div>';
}
I am trying to calculate how much a user has earned so it reflects on the users home page so they know how much their referrals have earned.
This is the code I have.
$get_ref_stats = $db->query("SELECT * FROM `members` WHERE `referral` = '".$user_info['username']."'");
$total_cash = 0;
while($ref_stats = $get_ref_stats->fetch_assoc()){
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."' UNION SELECT * FROM `completed_repeat` WHERE `user` = '".$ref_stats['username']."'");
$countr_cash = $get_ref_cash->fetch_assoc();
$total_cash += $countr_cash['cash'];
$countr_c_rate = $setting_info['ref_rate'] * 0.01;
$total_cash = $total_cash * $countr_c_rate;
}
It worked fine when I just had
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."'");
but as soon as I added in the UNION it no longer calculated correctly.
For example, there is 1 entry in completed and 1 entry in completed_repeat both of these entries have a cash entry of 0.75. The variable for $countr_c_rate is 0.10 so $total_cash should equal 0.15 but instead it displays as 0.075 with and without the UNION it acts as if it is not counting from the other table as well.
I hope this makes sense as I wasn't sure how to explain the issue, but I am very unsure what I have done wrong here.
In your second query instead of UNION you should use UNION ALL since UNION eliminates duplicates in the resultset. That is why you get 0.075 instead of 0.15.
Now, instead of hitting your database multiple times from client code you better calculate your cash total in one query.
It might be inaccurate without seeing your table structures and sample data but this query might look like this
SELECT SUM(cash) cash_total
FROM
(
SELECT c.cash
FROM completed c JOIN members m
ON c.user = m.username
WHERE m.referral = ?
UNION ALL
SELECT r.cash
FROM completed_repeat r JOIN members m
ON r.user = m.username
WHERE m.referral = ?
) q
Without prepared statements your php code then might look like
$sql = "SELECT SUM(cash) cash_total
FROM
(
SELECT c.cash
FROM completed c JOIN members m
ON c.user = m.username
WHERE m.referral = '$user_info['username']'
UNION ALL
SELECT r.cash
FROM completed_repeat r JOIN members m
ON r.user = m.username
WHERE m.referral = '$user_info['username']'
) q";
$result = $db->query($sql);
if(!$result) {
die($db->error()); // TODO: better error handling
}
if ($row = $result->fetch_assoc()) {
$total_cash = $row['cash_total'] * $setting_info['ref_rate'];
}
On a side note: make use of prepared statements in mysqli instead of building queries with concatenation. It's vulnerable for sql-injections.
With $countr_cash = $get_ref_cash->fetch_assoc(); you only fetch the first row of your result. However, if you use UNION, you get in your case two rows.
Therefore, you need to iterate over all rows in order to get all values.
Ok, So there is only one row in members table. You are iterating only once on the members table. Then you are trying to get rows using UNION clause which will result in two rows and not one. Then you are just getting the cash column of the first row and adding it to the $total_cash variable.
What you need to do is iterate over the results obtained by executing the UNION query and add the $total_cash variable. That would give you the required result.
$get_ref_stats = $db->query("SELECT * FROM `members` WHERE `referral` = '".$user_info['username']."'");
$total_cash = 0;
while($ref_stats = $get_ref_stats->fetch_assoc()){
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."' UNION SELECT * FROM `completed_repeat` WHERE `user` = '".$ref_stats['username']."'");
while($countr_cash = $get_ref_cash->fetch_assoc()){
$total_cash += $countr_cash['cash'];
}
$countr_c_rate = $setting_info['ref_rate'] * 0.01;
$total_cash = $total_cash * $countr_c_rate;
}