PHP Sum a value in while loop, but with conditions - php

I have two tables to be joined, 1 is user and 1 is attendance.
TABLE : attendance
id userId totalHours
1 1 0745
2 3 0845
3 1 0945
TABLE : user
id name departmentId
1 John 2
2 Sean 2
3 Allan 2
Not every user have attendance record (their totalHours)
But I need to query by userId WHERE departmentId = XXXX and SUM each of their totalHours that exist, without neglecting the userId without any record in attendance.
So far I made this:
$result = mysqli_query($con,"SELECT * FROM user WHERE departmentId = 2");
while($row = mysqli_fetch_array($result))
{
$id = $row['userId'];
$result2 = mysqli_query($con,"SELECT * FROM attendance WHERE userId = $id");
while($row2 = mysqli_fetch_array($result2))
$totalHours = 0;
{
$totalHours = $row2['totalHours'];
$grandTotal += $totalHours;
$totalHoursInHHmm = substr_replace($totalHours,":",2,0);
$parsed = date_parse($totalHoursInHHmm);
$toSeconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60;
$total += $toSeconds;
$init = $total;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
}
echo "$hours:$minutes";
}
The result shows all the user in the department, and did SUM all the totalHours for each userId , but what was wrong is, there are userId without any attendance still have the SUM value shown, inheriting previous total Sum
Any help is appreciated :)

I need to query by userId WHERE departmentId = XXXX and SUM each of
their totalHours that exist, without neglecting the userId without any
record in attendance.
To show the hours for all users in a given department, even users w/o rows in the attendance table, use a LEFT JOIN
Use (CAST(totalHours AS UNSIGNED) % 100)/60 + FLOOR(CAST(totalHours AS UNSIGNED)/100) to convert your varchar hours+minutes to a single number of hours.
$query = "SELECT u.id,
SUM((CAST(totalHours AS UNSIGNED) % 100)/60 + FLOOR(CAST(totalHours AS UNSIGNED)/100)) grandTotal
FROM user u
LEFT JOIN attendance a
ON u.id = a.userId
WHERE u.departmentId = 2
GROUP BY u.id";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
print $row['id'] . ' ' . $row['grandTotal'];
}

try this, just in the first while you wont need both.
SELECT TIME_FORMAT(sum(STR_TO_DATE(a.totalHours, '%i')),'%H:%i') as sum, u.id, u.name FROM user AS u LEFT JOIN attendance AS a ON a.userId = u.id WHERE u.departmentId = 2 AND u.id = $user_id GROUP by u.id;
Update, try that not sure if it will work I cant test it right now but refer to this question.
how to convert weird varchar "time" to real time in mysql?
Once you get the right query working it will be really easy in php to do the rest. The DB should do this work, although the schema is not ideal here..

OK! It's happening because, the users that doesn't have any attendance isn't passing through the second while, then the values aren't being restarted. You can correct this simply setting $grandTotal after you echo it. Like this:
$result = mysqli_query($con,"SELECT * FROM user WHERE departmentId = 2");
while($row = mysqli_fetch_array($result))
{
$id = $row['userId'];
$result2 = mysqli_query($con,"SELECT * FROM attendance WHERE userId = $id");
while($row2 = mysqli_fetch_array($result2))
{
$totalHours = 0;
$totalHours = $row2['totalHours'];
$grandTotal += $totalHours
}
echo $grandTotal;
$grandTotal = 0;
}

What I understood from the question is NOT to neglect those userid even if they do not have their attandance record. In this scenario I have 2 Options to be chosen ...
1.
$result = mysqli_query($con,"SELECT * FROM user WHERE departmentId = 2");
while($row = mysqli_fetch_array($result))
{
$id = $row['userId'];
$result2 = mysqli_query($con,"SELECT * FROM attendance WHERE userId = $id");
$grandTotal=0;
while($row2 = mysqli_fetch_array($result2))
$totalHours = 0;
{
$totalHours = $row2['totalHours'];
$grandTotal += $totalHours
}
echo $grandTotal;
}
2.
$result = mysqli_query($con,"SELECT * FROM user WHERE departmentId = 2");
while($row = mysqli_fetch_array($result))
{
$id = $row['userId'];
$result2 = mysqli_query($con,"SELECT * FROM attendance WHERE userId = $id");
while($row2 = mysqli_fetch_array($result2))
$totalHours = 0;
{
$totalHours = $row2['totalHours'];
if($totalHours<=0)
$grandTotal=0;
$grandTotal += $totalHours
}
echo $grandTotal;
}

Move $totalhours = 0 within the curly braces {}.
Set $hours = $minutes = 0 at the top of the second while loop (where you set $totalhours = 0)
**If you don't reset $hours and $minutes, users who don't have attendance will get the old values.

Related

How to join 4 tables "many to one" correctly, in sql?

good morning. I need to create a query that joins me 4 tables: recipes, food_recipes, prices_food AND users
tables
Currently what I do is:
search for recipes together with their user
inside I look for information on their food
and inside, in each iteration, I look for the information on the price of the food that the user entered
If the user did not enter any price, I look for the average of all the prices of people in the same country on certain dates
If the number of people who entered that price does not exceed the minimum, then the total price of the prescription will be 0
and it works very well. But I need everything to be in the same query to be able to filter for the price.
Try to create the query, with inner join and left join, but either way I don't get the result I need. Could you give me some guidance on what the correct syntax would be like? please
$wsqli="SELECT * from recipes
INNER JOIN users
on recipes.id_user = users.id_user
where $where
order by recipes.date desc
limit $limit
OFFSET $offset ";
$result = $linki->query($wsqli);
if($linki->errno) die($linki->error);
while($row = $result->fetch_array()){
$precio_receta = recipe_price($id_recipe);
}
function recipe_price($id_recipe)
{
$current_date = date('Y/m/d', strtotime('+1 day'));
$previous_date = date('Y/m/d', strtotime('-8 month'));
$price_recipe = 0;
$wsqli="SELECT * from recipes_foods
where id_recipe='$id_recipe' ";
$result = $linki->query($wsqli);
if($linki->errno) die($linki->error);
while($row = $result->fetch_array()){
$weight = $row['weight'];
$fdcId = $row['fdcId'];
$wsqli="SELECT * from foods_prices
where fdcId='$fdcId' and id_user='$id_user_session' and (foods_prices.date between '$previous_date' and '$current_date')";
$result2 = $linki->query($wsqli);
if($linki->errno) die($linki->error);
if($row = $result2->fetch_array()){
$price_recipe = $price_recipe + (($row['price'] / 1000) * $weight);
}else{
$wsqli="SELECT
COUNT(*) as quantity_prices,
AVG(price) as average_price
from foods_prices
inner join users
on users.id_user = foods_prices.id_user
where fdcId='$fdcId'
and country='$user_country'
and (foods_prices.date between '$previous_date' and '$current_date')";
$result2 = $linki->query($wsqli);
if($linki->errno) die($linki->error);
if($row = $result2->fetch_array()){
if ($row['quantity_prices'] > 50) {
$price_recipe = $price_recipe + (($row['average_price'] / 1000) * $weight);
}else{
$price_recipe = 0;
return $price_recipe;
break;
}
}else{
$price_recipe = 0;
return $price_recipe;
break;
}
}
}
return $price_recipe;
}
I have already managed to gather all the data in a single query.
$wsqli="SELECT *
from recipes
left JOIN recipes_foods
on recipes_foods.id_recipe = recipes.id_recipe
left JOIN foods_prices
on foods_prices.fdcId = recipes_foods.fdcId
left JOIN users
on users.id_user = foods_prices.id_user
where country='AR'
order by recipes.date desc";
$result = $linki->query($wsqli);
if($linki->errno) die($linki->error);
while($row = $result->fetch_array()){
var_dump($row);
}
but I still can't:
know if the quantity of prices entered for that food is greater than or equal to that required (min. 50). Try "where COUNT (price)> 50" but it says "Invalid use of group function"
If the quantity of prices IS LESS than required, stop last in the results (or do not show)
If the quantity of prices is greater than required .... Order by price. Adding "order by COUNT (price) desc" reduces the results obtaining only the first one.

How to update table using sequence in variable for each record one by one php

I have all records in sequence from 1 onwards for each record displayed but wish to update each one with that sequence in a field within the table.
Any help?
if(isset($_POST['setorder']))
{
$i = 1;
//$today = date('Y-m-d', strtotime('-1 day'));
$routesql = $mysqli->query("SELECT * FROM routes WHERE status = 1");
while ($routerows = $routesql->fetch_array())
{
$rname = $routerows['routename'];
$routejobs = $mysqli->query("select tracking.*, district.* from tracking left join district on tracking.street = district.street
where tracking.date = '$today' AND tracking.status = 2 and route = '$rname' order by district.sortorder asc");
while ($routejrows = $routejobs->fetch_array())
{
echo $i.' - '.$routejrows['joborder'].' - '.$routejrows['addressto'];
echo '<br/>';
$i++;
}
}
}

how get and compare two mysql data?

table 1
two column >> paid - order_num1
table 2
two column >> order_num2
I want get order_num2 value from table 2 and
update paid(insert paid = 1) in table one with same order_num value
If order_num1=order_num2 then paid = 1 in table 1
$q = mysql_query("select order_num2 from table2 where samevalue = samevalue ");
$x = mysql_fetch_row($q);
mysql_query("update table1 set paid=1 where order_num1='$x['order_num2']'");
But it does not work!
First get from one table and update paid from another table if order_num have same value
Try
$table2 = mysqli_query("SELECT * FROM table2");
$row = mysqli_fetch_array($table2);
$num2 = $row['order_num2'];
$table1 = mysqli_query("SELECT * from table1");
$roww = mysqli_fetch_array($table1);
$num1 = $row['order_num1'];
if ($num2 == $num1) {
$updateDB = mysqli_query("UPDATE table1 SET paid = 1 WHERE order_num1 = '$num2'");
} else {
//Not equal so the paid column wont get updated
}

mysql count where row = 0

I am trying to show a count but only where the column deleted is equal to 0
here is what i have tried
$result=mysql_query("SELECT * FROM users where deleted=0")or die('Error ' );
$counter = mysql_query("SELECT COUNT(*) as personID FROM users");
$row = mysql_fetch_array($result);
$personID = $row['personID'];
$personFname = $row['personFname'];
$personSname = $row['personSname'] ;
$llmail = $row['llmail'];
$mainadmin = $row['mainadmin'];
$delete = $row['delete'];
$num = mysql_fetch_array($counter);
$count1 = $num["personID"];
This shows a count of 4 however of the 4, 2 are deleted so it should only show 2 if this makes sense?
SELECT COUNT(*) as personID FROM users WHERE deleted=0

Get highest sum value from two tables

Here is my code:
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
<tr> <?php echo $sum; ?></tr>
}while($row_query1 = mysql_fech_assoc($result));
I need to get the highest value of $sum from this loop. Can anyone help?
You can do like this.. take a temporary variable($temp) which can have check upon the sum variable($sum).
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
$temp = 0;
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
if($temp < $sum)
$temp = sum;
echo "<tr>$sum</tr>";
}while($row_query1 = mysql_fech_assoc($result));
echo "maximum sum :".$temp;
I would advice doing a JOIN instead of performing the sub queries yourself:
select user, sum(column) + sum(column1) as total
from table1
INNER JOIN table2 ON names = user
GROUP BY user
The rest should be straightforward in code.

Categories