Generate Sum of Occurrence of an action in PHP - php

I need assistance on how to generate the sum of occurrence of an exception from an entries that is capture daily on a weekly basis group by the offenders. take a look at my code which works for the offender but summing the offence totally instead of summing it for individual offender.
<tr>
<th>S/N</th>
<th>NAME</th>
<th>STAFF ID</th>
<th>ABS</th>
<th>BRK</th>
<th>BV</th>
<th>DUI</th>
<th>OS</th>
<th>OTH</th>
<th>Details of Other Offences</th>
</tr>
<?php
$get = mysqli_query($connection,"SELECT * FROM tab_incidence WHERE mainloc='$loc' AND cast(created_at as date) BETWEEN '$td1' AND '$td2' AND weekno='$wk' AND team='$tm' GROUP BY op ORDER BY fltno");
$c=0;$sumAbs=0;$sBrk=0;$sBv=0;$sDui=0;$sOs=0;$sOth=0;
while($rw = mysqli_fetch_array($get)){
$c++;
echo "<tr>";
echo "<td nowrap='nowrap'>". $c."</td>";
echo "<td nowrap='nowrap'>".$rw['op']."</td>";
echo "<td nowrap='nowrap'>".$rw['staffno']."</td>";
echo "<td nowrap='nowrap'>" .($rw['details']=='ABS'?$sumAbs=$sumAbs+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='BRK'?$sBrk=$sBrk+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='BV'?$sBv=$sBv+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='DUI'?$sDui=$sDui+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='OS'?$sOs=$sOs+1:'0')."</td>";
echo "<td nowrap='nowrap'>". ($rw['details']=='OTH'?$sOth=$sOth+1:'0')."</td>";
echo "<td nowrap='nowrap'>". $rw['svalcom']."</td>";
echo "</tr>";
};}?>
I wantit to be able to sum each offence for each staff based on the weekno which is stored as week1, week2, week3. Note in each week, i have a record for each day that the offence is committed which will fall into week1 or 2 or 3 or 4.Any clue or assistance will be appreciated.

Step one: Find the staff who made any incident within a certain date (the week you are looking for)
SELECT distinct(staffno) as staff FROM tab_incidence WHERE mainloc='$loc' AND cast(created_at as date) BETWEEN '$td1' AND '$td2' AND weekno='$wk' AND team='$tm'
Step 2: Loop the result
while($rw = mysqli_fetch_array($get)){ // Pass by every staff
// Query for ABS is
SELECT count(id) as number FROM tab_incidence WHERE mainloc='$loc' AND cast(created_at as date) BETWEEN '$td1' AND '$td2' AND weekno='$wk' AND staffno='$rw["staff"]' AND details = 'ABS' // This will return the number of ABS offense per staff
}
Each type would require a query.

Related

Want to show checkbox for each line

Currently, in our office website, there is a userinput textbox and after inserting, results from database will be shown below. There are 4 results Lot ID, Product, EWSFLOW and Zone.Among them, only zone is different. I want to do that Lot ID, Product and EWSFlow must show at once and if that entered values have 5 different zones, Zone must shown Zone: 1,2,3,4,5. << First problem has been solved. And right now, I tried to add check boxes for each zone and checkbox must shown beside each zone. But currently, checkboxes are showing at the top. Also, count of the checkboxes must be same as Zones. lets say if the inserted value have 5 zones, it has to show 5 checkboxes besides of it (Example: Zone : [checkbox] 1).
Checkboxes are showing at top
echo "<table id='corwafer'>";
$arr = array();
while ($row = mysqli_fetch_assoc($result1)) {
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
$key = $field1name + ":" + $field2name + ":" + $field3name;
if (!in_array($key, $arr)){
echo "<tr>";
echo "<th >Lot ID:</th>";
echo "<td >$field1name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Product:</th>";
echo "<td>$field2name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>EWSFLOW: </th>";
echo "<td>$field3name</td>";
echo "</tr>";
array_push($arr, $key);
}
echo "<tr>";
echo "<th>Zone:</th>";
echo "<input type='checkbox' name='chkzone' value='chkzone'>";
echo "<td>$field4name</td>";
echo "</tr>";
}
echo "</table>";
You can define an array and put lotid, product and ewsflow into it as merged inside the loop. Then before echoing check if it's already used before :
$arr = array();
while ($row = mysqli_fetch_assoc($result1)) {
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
$key = $field1name + ":" + $field2name + ":" + $field3name;
if (!in_array($key, $arr)){
echo "<tr>";
echo "<th >Lot ID:</th>";
echo "<td >$field1name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Product:</th>";
echo "<td>$field2name</td>";
echo "</tr>";
echo "<tr>";
echo "<th>EWSFLOW: </th>";
echo "<td>$field3name</td>";
echo "</tr>";
array_push($arr, $key);
}
echo "<tr>";
echo "<th>Zone:</th>";
echo "<td>$field4name</td>";
echo "</tr>";
}
You can change your query and use GROUP BY feature of MySQL. Below is the query. Ignore any spelling mistakes.
$sql = "SELECT lotid, product, ewsflow, GROUP_CONCAT(zone) FROM productdb.tbl_correlationwafer WHERE lotid = ? GROUP BY lotid, product, ewsflow ORDER BY lotid";
$pq = $mysqli->prepare($sql);
$pq->bind_param('i', $productlotid);
$pq->execute();
$result = $pq->get_result();
$data = $result->fetch_all();
GROUP_CONCAT() function returns a string with concatenated non-NULL value from a group.
GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
You can accomplish the desired output in a much simpler fashion if you were to use group_concat in the SQL query to gather together the various zone columns into a formatted value - then the PHP really needs only process a single row in the recordset and display the desired table format.
The SQL takes advantage of a prepared statement to help mitigate SQL injection - matters not that it is an internal website IMO - always better to be secure!
$sql='SELECT
`lotid`,
`product`,
`ewsflow`,
group_concat( distinct `zone` order by `zone` asc separator ", " ) as `zone`
FROM `productdb`.`tbl_correlationwafer`
WHERE `lotid` = ?
ORDER BY `lotid`';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('s', $productlotid );
$stmt->execute();
$stmt->bind_result( $lotid, $product, $ewsflow, $zone );
$stmt->fetch();
printf('
<table id="corwafer">
<tr>
<th>Lot ID:</th>
<td>%1$s</td>
</tr>
<tr>
<th>Product:</th>
<td>%2$s</td>
</tr>
<tr>
<th>EWSFLOW:</th>
<td>%3$s</td>
</tr>
<tr>
<th>Zone:</th>
<td>%4$s</td>
</tr>
</table>',
$lotid,
$product,
$ewsflow,
$zone
);

Change cell color based on amount of time passed

So, I'm hitting a brick wall. What I'm trying to do is change the color of my "waiting" cell in my table based off the amount of time that has passed. When queried my "waiting" cell displays a time stamp in the format of 00:00:00. To make my coding more consistent and easier for the next guy who may come along and replace me. I'm querying a view that I created within my mysql database that updates my timestamp. So, all my html/php code has to do is query the view to pull in the information I want displayed.
I've scoured the internet and found several bits and pieces of code that it supposed to be able to change a cells color based on value. I've had a little bit of luck but have not gained the desired results. I either end up with cells that stay the same color and not change or find there is something wrong with the code that prevents the whole page from loading.
include 'config/database.php';
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$records_per_page = 5;
$from_record_num = ($records_per_page * $page) - $records_per_page;
$query = "SELECT ptfin, ptname, ptdob, pore, notes, labstat,
rtstat,radstat,waiting
FROM dashboard_view
WHERE ( labstat != '' AND labstat IS NOT NULL)
OR (radstat != '' AND radstat IS NOT NULL)
OR (rtstat != '' AND rtstat IS NOT NULL)
ORDER BY waiting DESC
LIMIT :from_record_num, :records_per_page";
$stmt = $con->prepare($query);
$stmt->bindParam(":from_record_num", $from_record_num, PDO::PARAM_INT);
$stmt->bindParam(":records_per_page", $records_per_page, PDO::PARAM_INT);
$stmt->execute();
$num = $stmt->rowCount();
$curDate = time();
$mysqlTimestamp = $row['waiting']; //This is the piece of code that is giving me issues.
$dif = strtotime($curdate) - strtotime($mysqlTimestamp);
if($num>0)
if($dif < 10000) {
$tdStyle='background-color:green;';
} else {
$tdStyle='background-color:red;';
}
echo "<table class='table table-hover table-responsive table-bordered'>";
echo "<tr>";
echo "<th>FIN#</th>";
echo "<th>Name</th>";
echo "<th>PorE</th>";
echo "<th>Notes</th>";
echo "<th>Modalities</th>";
echo "<th>Waiting</th>";
echo "</tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td width=15>{$ptfin}</td>";
echo "<td width=100>{$ptname}</td>";
echo "<td width=5>{$pore}</td>";
echo "<td width=200>{$notes}</td>";
echo "<td width=170><img src=".$labstat." ><img src=".$rtstat." ><img src=".$radstat." ></td>";
echo "<td style=\"$tdStyle\" width=50>{$waiting}</td>";
//echo "<td width=5>{$dif}</td>"; code for testing visual output of timestamp mathmatics
echo "</tr>";
}
echo "</table>";
What I would like to have happen is if the timestamp is less than 10 minutes the cell displays green. If the timestamp falls into the range of 10 to 15 minutes to the cell displays yellow. If the timestamp is greater than 15 minutes the cell displays red.

Subtract values in one column by using filter of other two

I am trying to subtract values of one column. The data is big so I need to filer it. Query works but it does not display correct results.
First I choose filter where I type height and warehouse(checkboxes are used to allow multiple selection for warehouse).
$debljina=[$_POST'debljina'];
Then I made query for warehouse
if (!empty($skladiste)) {
$sklad="SELECT `ReprMatId` FROM `jos_ib_repromaterijali` WHERE `ReprMatSkladiste` = '$skladiste[0]'";
if(sizeof($skladiste)>0){
for ($i=0; $i<sizeof($skladiste); $i++) {
$sklad.="OR ReprMatSkladiste = '$skladiste[$i]'";
}
}
}
echo "<table border='2' style='border-collapse: collapse;border-color: silver;'>";
echo "<tr style='font-weight: bold;'>";
echo "<td width='100' align='center'>Ukupna količina repromaterijala na skladištu DEBLJINA: $debljina (kg)</td>";
$total = " SELECT SUM(ReprMatTrenutnaKolicina) FROM `jos_ib_repromaterijali` WHERE `ReprMatDebljina`= '$debljina' AND
jos_ib_repromaterijali.ReprMatId IN(".$sklad.") ";
/echo $total;
$totalquantity=mysqli_query($con, $total);
while($row=mysqli_fetch_array($totalquantity))
{
echo "<tr'>";
echo "<td align='center' width='400' height='30'>" . $row['SUM(ReprMatTrenutnaKolicina)'] . "</td>";
echo "</tr>";
}
echo "</table>";
when I echo total quantity I get query:
SELECT SUM(ReprMatTrenutnaKolicina) FROM `jos_ib_repromaterijali` WHERE `ReprMatDebljina`= '0.5' AND jos_ib_repromaterijali.ReprMatId IN(SELECT `ReprMatId` FROM `jos_ib_repromaterijali` WHERE ReprMatSkladiste = '1' OR ReprMatSkladiste = '6')
I get result but something is wrong and I can not figure it out.. Any help or advice is appreciated.
You cannot do $row['SUM(ReprMatTrenutnaKolicina)']
Change your select statement in your query to:
SELECT SUM(ReprMatTrenutnaKolicina) as NUM [...]
And then do the following to access the value:
$row['NUM']

How to see what reports are received more than 2 days later than they were finished in SQL

Im trying to do a query to show only reports which were received more than two days after their end completion date, within a specified date range. I have this so far but cant quite figure out how to get the 'more than 2 days' part right. can anyone help me please.
$result = mysqli_query($con, "SELECT *
FROM tcards.vtmastertrail
INNER JOIN tcards.vtcards ON tcards.vtcards.id = tcards.vtmastertrail.card_id
WHERE tcards.vtcards.colour = 'Beige' AND datetime_report_received > (inspdate_end + 2) AND
inspdate_end >= '2014-04-01' AND inspdate_end <= '2014-04-30'
ORDER BY tcards.vtmastertrail.inspdate_end, datetime_report_received");
current output is a table like so:
echo "<table border='1'>
<tr>
<th>Report End Date date</th>
<th>Received Report date</th>
<th>Job Finish Date</th>
<th>Client</th>
<th>Client Code</th>
<th>Employee</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['inspdate_end'] . "</td>";
echo "<td>" . $row['datetime_report_received'] . "</td>";
echo "<td>" . $row['datetime_completed_report'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['client_code'] . "</td>";
echo "<td>" . $row['employee'] . "</td>";
echo "</tr>";
}
echo "</table>";
This info is being pulled by the query and displayed in my table but all the records 'datetime_report_received' is not 2 days more than the 'inspdate_end'. It is just displaying all records which have a 'inspdate_end within the daterange ive specified. Same result as i get if i remove the + 2) part of the query. so the +2) part must'nt be doing anything
cant post pic as i dont have good enough rep.
If you used the PHP function substr() to get the last two characters of the date in the database (so substr($variable, -2)) then you could add 2 to that as you have done in your code to check whether the date was before or after today.
It might be worth storing the time as well because with this currently, if I had a record in the database submitted at 2014-07-27 23:59 and I checked it at 2014-07-29 00:01, it would still return that two days have passed from the original submission of the entry to the database, when in reality only 1 day and 2 minutes have passed.

Bundling information by date

I have a pretty good idea of how to do this, but I'm not exactly sure... how to do it , if that makes sense. This is still my first day (going on second without sleep) of learning PHP and I'm trying to complete this project before I call it quits. This is actually all that's left before I can call it quits and be happy with myself. So here's the thing.
I know I've asked quite a few questions today, hopefully this is the last one..
Currently my code pulls information from my database and displays it into a table, like so:
Now, this is great for the feature where I want to list the last 15 transactions, which is what my following code does, please excuse anything that's not done efficiently as it's my first day.
<html>
<table border="1">
<tr>
<th>Transaction Date</th>
<th>Transaction Amount</th>
<th>Item Name</th>
<th>Quantity</th>
</tr>
<?php
require_once 'Config.php';
require_once 'Connection.php';
$totalTransactions = 0;
$totalProfit = 0;
$testquery = "SELECT * FROM $tbl_name WHERE DATE($tbl_name.Date)
BETWEEN DATE_SUB(CURDATE(), INTERVAL 15 DAY) AND CURDATE()";
$results = mysql_query($testquery) or die (mysql_error());
while($row = mysql_fetch_array($results))
{
$totalTransactions += 1;
$totalProfit += $row[$ROW_AMOUNT];
echo "<tr>";
echo "<td align='center'>".$row[$ROW_DATE] . "</td>";
echo "<td align='center'>$". number_format($row[$ROW_AMOUNT], 2) . "</td>";
echo "<td align='center'>null</td>";
echo "<td align='center'>null</td>";
echo "<tr>";
}
echo "<tr>";
echo "<td align='center'><strong>SUM:</strong></td>";
echo "<td align='center'><strong>$".number_format($totalProfit, 2)."</strong></td>";
echo "<td align='center'><strong> </strong></td>";
echo "<td align='center'><strong> </strong></td>";
echo "<tr>";
?>
</table>
</html>
Now, I'm trying to figure out how I can group it like such in a table
[Day] - [Sum]
I understand how to get the sum for the data, obviously because that's what the script above does for the last 15 transactions, but how about grouping them together?
an example of the output I'm looking for is like this (This was done in pure HTML and is just an example of what I'm trying to achieve)
To re-word my question more efficiently, I'm trying to create another table that shows the sum for each date that there is "Transactions" for.
You have to group your columns using the GROUP BY clause and then aggregate the sum of Transaction Amount:
SELECT Date, SUM([Transaction Amount])
FROM $tbl_name
WHERE DATE($tbl_name.Date)
BETWEEN DATE_SUB(CURDATE(), INTERVAL 15 DAY) AND CURDATE()
GROUP BY Date
Please note that you may have to put quotes or something else around the column name Transaction Amount, this is TSQL syntax, I'm not sure how it's done in MySQL.

Categories