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.
Related
I'm trying to find a way to increase a number in my database which I enter manually based on another number that is updated automatically from a device.
In my database I have a few columns, but the one that matters are
cancelled_meter mec_in demult.
``cancelled_meter`` is the column that is updated automatically
``mec_in`` is the column that is input manually
``demult`` is the column that is also updated automatically
These columns are all numbers (eg. cancelled_meter = 428080.00, mec_in = 2174827.00 and demult is usually 1, 100 or 1000.
Here's something I was trying to do in PHP:
<?php
$sql = "SELECT id, cancelled_meter, total_drop, mec_in, mec_out, demult, val_pct
FROM machtest ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th>
<th>Coin IN Meter</th>
<th>Coin OUT Meter</th>
<th>Demultiplication</th>
<th>Pt Value</th>
<th>Total IN</th>
<th>Total OUT</th>
</tr>";
while($row = $result->fetch_assoc()) {
$offset_in = $row["cancelled_meter"] - $row["mec_in"] * -1;
$abbs_in = abs($offset_in);
$round_in = abs($row["cancelled_meter"] / $row["demult"] + $abbs_in);
$offset_out = $row["total_drop"] - $row["mec_out"] * -1;
$abbs_out = abs($offset_out);
$round_out = abs($row["total_drop"] / $row["demult"] + $abbs_out);
echo "<tr>
<td>"
.$row["id"]."</td>".
"<td>"
.$row["cancelled_meter"]."</td>".
"<td>"
.$row["total_drop"]."</td>".
"<td>"
.$row["demult"]."</td>".
"<td>"
.$row["val_pct"]."</td>".
"<td>"
.$round_in."</td>".
"<td>"
.round($row["total_drop"] / $row["demult"] + $abbs_out)."</td>
<tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
This kind of works but I want to display mec_in which updates automatically when cancelled_meter changes and that only displays something else.
One more thing is that mec_in can be greater or lesser then cancelled_meter that's why I need a positive result.
I was trying something like mec_in = cancelled_meter / demult + some offset that's between cancelled_meter and mec_in.
I'm trying to figure this out, but I'm a beginner, so if anyone has some suggestions I would very much appreciate it.
PS. I was trying to calculate this on the php file but in the MySQL is good too if anyone knows how.
I don't know what wase in my head, but after adding this $total = abs($round_in - $row["offset_in"]); worked just fine. I got offset_in column by doing $round_in -
mec_in and then $round_in - $row["offset_in"]); wich gives the desired result. Thank you for your input.
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.
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.
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.
Here is my current code:
$varVeh=$_POST['Veh_num'];
$sql_HiScores = "SELECT
c.course_name as course,
e.distance as distance, e.score as score,
e.time as time, e.user as User
FROM hc_entries e
LEFT JOIN hc_course c on e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY course, score DESC";
$result_HiScores = mysql_query($sql_HiScores);
$sql_vehName="SELECT Veh_name FROM hc_vehicle_type WHERE Veh_num=$varVeh ";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th></tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
}
echo "</table>";
What I think I have to do is create a query that selects * from e.course that builds an array. Then cycle through the existing query with the array results. Finally, I would like to display individual tables for each course and limit it to the top 5 results for each course.
Can anyone confirm or deny my logic, and point me in a direction?
First of all, you shouldn't be using the mysql_ functions, they're deprecated. At the least, you should switch to mysqli_ (a pretty easy switch), or better, learn how to use PDO. It's a bit different and more involved to switch, but your code will be better and safer for it.
With that out of the way: your logic is pretty accurate. Limiting your results to the top 5 results for each course in one query isn't something that's easily done with SQL to my knowledge, so your plan is good: query a list of courses, then cycle through them with your existing query, running it once for each course, with a LIMIT 5 to get the top 5.
You might as well keep the table generation within this loop as well, since it's a table-per-course. You'd want to move the VehName query out of the loop, since you only need to run that once.
Also, some unsolicited PHP advice: any text outside of the tags will just be output directly, so take advantage of its built-in-templating and alternative syntax to make your table generation code nicer:
<?php
/* Gather your data here... */
?>
<table>
<tr><th>Best Scores for <?php echo $vehName['Veh_name'] ?></th></tr>
</table>
<table border='1'>
<tr>
<th>Course</th>
<th>Score</th>
<th>Distance</th>
<th>Player</th>
<th>Time</th>
</tr>
<?php while($row = mysql_fetch_array($result_HiScores)): ?>
<tr>
<td><?php echo $row['course'] ?></td>
<td><?php echo $row['score'] ?></td>";
<td><?php echo $row['distance'] ?></td>";
<td><?php echo $row['User'] ?></td>";
</tr>
<?php endwhile; ?>
</table>
put the entire table html inside the while loop and add 'LIMIT 5' to the end of your query