Get highest sum value from two tables - php

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.

Related

How to sum of MySQL table column in php?

I want to get the sum total of the table columns in my database.
I've tried using the following code but have not been successful.
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(value) AS value_sum FROM User_Table');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
echo $sum;
Thank you very much!!
I hope you try to find total number of record of a table of User_Table
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(your_column_name) AS value_sum FROM User_Table');
//or like the query for return last row that indicate total number of record
// id auto increment
$result = mysqli_query($link,'SELECT * FROM User_Table ORDER BY id DESC LIMIT 1;');
$row = mysqli_fetch_assoc($result);
$sum = $row['id'];
echo $sum;
// or using count
$result = mysqli_query($link,'SELECT COUNT(*) total_row FROM User_Table;');
$row = mysqli_fetch_assoc($result);
$sum = $row['total_row '];
echo $sum;
As of my understanding you need count the number of columns your database have. If I am not wrong, you may please use the query below
select * from information_schema.columns
where table_schema = '<YOUR DATABASE NAME>'
order by table_name,ordinal_position
Hope this helps. Thanks

Unable to get key value from a mysql multi-dimensional array

I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}

Order while loop data

I'm making a ranking system. But what I want is to order the results I get ($kn) from highest to lowest. How can I do this?
include "includes/core.inc.php";
require "includes/connect.inc.php";
$id = $_GET["id"];
$query = "SELECT * FROM submitted WHERE id= '$id'";
$query_run = $db->query($query);
while($row = mysqli_fetch_assoc($query_run)){
$name= $row["name"];
$sql = "SELECT * FROM submitted WHERE name= '$name' AND pending = 'Accept'";
$sql_run = $db->query($sql);
$count = $sql_run->num_rows;
$nums= "SELECT * FROM ranking WHERE name= '$name'";
$nums_run = $db->query($nums);
$num = $nums_run->num_rows;
$kn = ($count * 0.4) + (($num * 0.2) * 3);
echo '$name';
echo '$kn';
}
Looping over a list and querying each element is almost never a good idea. Instead, you can move the entire logic to the query, and then sort it there:
$query =
"SELECT s.name AS name, (cnt_submitted * 0.4) + ((cnt_ranking * 0.2) * 3) AS kn
FROM (SELECT name, COUNT(*) AS cnt_submitted
FROM submitted
WHERE id = '$id' AND
pending = 'Accept'
GROUP BY name) s
JOIN (SELECT name, COUNT(*) AS cnt_ranking
FROM ranking
GROUP BY name) r ON r.name = s.name
ORDER BY 2 DESC";
$query_run = $db->query($query);
while ($row = mysqli_fetch_assoc($query_run)) {
$name = $row["name"];
$kn = $row["kn"];
echo '$name';
echo '$kn';
}
Note:
The $id variable should probably be a bound variable in a prepared statement to safe-guard against SQL-injection attacks.
I left it as it was in the OP, though, since this is not the point of the question and I don't want to add additional confusion.
You can do it also in PHP:
$result = [];
while (...) {
.....
$kn = ($count * 4) + (($num * 2) * 30);
$result[] = [
'rank' => $kn,
'name' => $name
];
}
usort($result, function($a, $b) {
return $b['rank'] - $a['rank'];
});

PHP Sum a value in while loop, but with conditions

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.

MySQL SUM function

I'm trying to get the sum of a column.
My Schema is as below...
I'd like to get the SUM of 'bill'.
I have the following...
<?php
$uid = $_SESSION['oauth_id'];
$query = mysql_query("SELECT * FROM `users`, `income`, `outgoings` WHERE users.oauth_uid = '$uid' and income.user_id = '$uid' and outgoings.user_id = '$uid'") or die(mysql_error());
$result = mysql_fetch_array($query);
?>
Outgoings = <?php echo $result["SUM(total)"];
I'm not receiving any output, however. Can anybody see where I'm going wrong? There's definitely data in my table.
The SUM function must be used when deciding what to return from the select. Like so.
SELECT SUM(`bill`) FROM `users`, `income`, `outgoings` WHERE users.oauth_uid = '$uid' and income.user_id = '$uid' and outgoings.user_id = '$uid'
Try this if you don't want to do a SUM() query as already proposed by others:
<?php
$sum = 0;
while ($row = mysql_fetch_array($query)) {
$sum += $row['bill'];
}
?>
Outgoings = <?php echo $sum; ?>
But remember that you will need this if you want to reuse the same $query resultset:
<?php
mysql_data_seek($query , 0);
?>
Why not just query for the SUM directly? Like:
<?php
$uid = $_SESSION['oauth_id'];
$sum = mysql_query("SELECT SUM(`bill`) FROM `users` WHERE users.oauth_uid = '$uid'") or die(mysql_error());
?>
This query will get you the sum:
SELECT sum(bill) FROM `the_table`

Categories