I am working with laravel and i have a table with all the users attendances.
each row has a flag stating if the user logs in or out. I want to calculate the total working hours of user.
this is my table and sample data
id | user_id | date | timestamp | status |
1 | 1 | 2018-05-10 | 17:15:31 | out |
1 | 1 | 2018-05-10 | 13:15:31 | in |
1 | 1 | 2018-05-10 | 12:15:31 | out |
1 | 1 | 2018-05-10 | 08:01:31 | in |
I want to calculate the total working hours
$logs = DB::table('attendances as at')
->join('infos as in','in.user_id','=','at.user_id')
->select('in.name','in.avatar','at.*')
->orderBy('id','desc')
->where('at.user_id',$id)
->get();
$total_hours = [];
for($i=0; $i < count($logs)-1; $i++ ){
if($logs[$i]->status == 'out'){
$dattime1 = new DateTime($logs[$i]->dt.' '. $logs[$i]->time);
$dattime2 = new DateTime($logs[$i+1]->dt.' '. $logs[$i+1]->time);
$total_hours[] = $dattime1 ->diff($dattime2);
}
}
$working_hours = array_sum($total_hours);
Is this the best way to achieve accurate results? Please help.
Thanks
Can you try like this?
$time1 = "17:15:00";
$time2 = "00:30:00";
$strtotime1 = strtotime($time1);
$strtotime2 = strtotime($time2);
$o = ($strtotime1) + ($strtotime2);
echo $time = date("h:i:s A T",$o);
Output will be like this:
05:45:00 PM UTC
Related
I have a leave date data in one month with various types of dates I try to match the data by date this month. when I make it based on row data only one date appears. I am a little less aware of the logic if it is an array.
My table
| ID | id | start_date | end_date |
| ____|________|______________|______________|
| 1 | x1 | 2018-11-05 | 2018-11-05 |
| 1 | x1 | 2018-11-12 | 2018-11-15 |
| 3 | x1 | 2018-11-19 | 2018-11-21 |
My script
$timesheet = $this->db->select('*')
->where('MONTH(start_date)', 11)
->where('YEAR(start_date)', 2018)
->where('id', 'x1')
->get();
$result = $timesheet->row_array();
$day_start=date_create($result['start_date']);
$day_end=date_create($result['end_date']);
for ($x = 1; $x <= 30; $x++) {
if($x >=$day_start->format('d') and $x <= $day_end->format('d')){
echo "<td class='bg-warning'>Y</td>";
}else{
echo "<td>N</td>";
}
}
/** MY result data **/
| Date | ... | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | ... |
----------------------------------------------------------------
| Result| ... | N | N | N | Y | Y | N | N | N | N | ... |
/** the results I expected **/
| Date | ... | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | ... |
----------------------------------------------------------------
| Result| ... | N | Y | N | Y | Y | N | Y | Y | Y | ... |
If you want to merge all of the records together, you will need to build up an array of the days (I create it using array_fill() and set each one to "N" to start).
You then iterate over each result row and add in the Y's to the appropriate elements. You then loop over from the start to end day using a for() loop to fill in the days with a 'Y'.
Finally you can output the $dates array which has all of the various rows added into it.
$dates = array_fill(1, 30, "N");
foreach ($timesheet->result_array() as $result) {
$start = (int)$result['start_date']->format('d');
$end = (int)$result['end_date']->format('d');
for ( $i = $start; $i <= $end; $i++ ) {
$dates[$i] = "Y";
}
}
foreach ( $dates as $day ) {
if($day == "Y") {
echo "<td class='bg-warning'>Y</td>";
}else{
echo "<td>N</td>";
}
}
You will probably want to change the array_fill() to have the correct number of days for the month you are working with, but this is something you can sort out as and when you need it.
I'm developing a pharmacy store project, but I have a problem of determining the total number of drugs that expired. From DB I have:
+----+----------+--------+------------+
| id | drug_nam | amount | exp |
+----+----------+--------+------------+
| 1 | M and T | 200 | 04/15/2016 |
| 2 | VIT C | 20 | 05/25/2016 |
| 3 | Pana | 10 | 01/03/2016 |
| 4 | Lonat | 1200 | 08/25/2017 |
| 5 | ProC | 100 | 05/25/2017 |
+----+----------+--------+------------+
what I need here is a line of PHP script that will count the numbers of expired drugs from DB. using <?php $d = date('m/d/Y'); ?> to determine it from DB.
I used the code below but it count only 2
<?php
$d = date('m/d/Y');
$result = mysqli_query($conn, "SELECT count(exp) FROM products where exp < $d ");
while($row = mysqli_fetch_array($result))
{
echo $row['count(exp)'];
}
You should convert your string date representation to date value if you want to filter by date but not by string.
This query should work:
SELECT count(exp) FROM products where STR_TO_DATE(exp, '%d/%m/%Y') < $d
The main drawback is mysql can't use index in this case. One of the solution is to convert your column from varchar(50) to DATETIME. In this case you can use your original query.
From your table it seems you used some sort of text or varchar for you exp column. Cause mysql date format should be like yyyy-mm-dd. Please change your exp column to date and change the below line
$d = date('m/d/Y');
to
$d = date('Y-m-d');
That should be good.
I have the following table structure and using Yii2 ActiveRecord methods I'd like to extract the number of bookings (OrderLine) a supplier has for each day for the next week (0 entries also required). So some way of getting a row per day per supplier, with num_bookings or potentially 0 depending on the supplier.
/--------------------\ /------------\
| OrderLine |------------------|Availability|
|--------------------| 0..n 1 |------------|
|ID {PK} | |ID {PK} |
|availabilityID {FK} | |start |
|line_status | \------------/
|supplierID {FK} |
\--------------------/
| 1
|
|
| 1
/----------\
| Supplier |
|----------|
|ID {PK} |
\----------/
Querying the database directly, using DAO, with the following SQL gives me (almost) the desired result,
select count(ol.ID) as num_bookings,
day(from_unixtime(a.start)) as order_day,
ol.supplierID
from order_line ol left join
availability a on ol.availabilityID = a.ID
where ol.line_status = "booked"
and a.start >= 1451952000 //magic number for midnight today
and a.start <= 1452556800 //magic number for seven days from now
group by order_day, ol.supplierID;
something along the lines of
------------------------------------
| num_bookings|order_day|supplierID|
------------------------------------
| 1 | 5 | 3 |
| 2 | 5 | 7 |
| 1 | 6 | 7 |
| 1 | 7 | 7 |
------------------------------------
So there should be entries of 0 for the days the given Supplier has no bookings, like so
------------------------------------
| num_bookings|order_day|supplierID|
------------------------------------
| 1 | 5 | 3 |
| 0 | 6 | 3 |
| 0 | 7 | 3 |
| 2 | 5 | 7 |
| 1 | 6 | 7 |
| 1 | 7 | 7 |
------------------------------------
[days 8+ omitted for brevity...]
I've got some php/Yii code which will [eventually] give me something similar but involves multiple queries and database connections as follows,
$suppliers = Supplier::find()->all(); // get all suppliers
$start = strtotime('tomorrow');
$end = strtotime('+7 days', $start); // init times
// create empty assoc array with key for each of next 7 days
$booking_counts[date('D j', $start)] = 0;
for ($i=1; $i<7; ++$i) {
$next = strtotime('+'.$i." days", $start);
$booking_counts[date('D j', $next)] = 0;
}
foreach ($suppliers as $supplier) {
$bookings = OrderLine::find()
->joinWith('availability')
->where(['order_line.supplierID' => $supplier->ID])
->andWhere(['>=', 'availability.start', $start])
->andWhere(['<=', 'availability.start', $end])
->andWhere(['order_line.line_status' => 'booked'])
->orderBy(['availability.start' => SORT_ASC])
->all();
$booking_count = $booking_counts;
foreach ($bookings as $booking) {
$booking_count[date('D j', $booking->availability->start)] += 1;
}
}
This gives me an array for each supplier with the count stored under the appropriate day's index but that feels quite inefficient.
Can I refactor this code to return the desired data with fewer database calls and less 'scaffold' code?
This could be is the trasposition of your firt select
$results = OrderLine::find()
->select('count(order_line.ID) as num_bookings, day(from_unixtime(availability.start)) as order_day', order_line.supplierID )
->from('order_line')
->leftjoin('availability', 'order_line.availabilityID = availability.ID')
->where( 'order_line.line_status = "booked"
and a.start >= 1451952000
and a.start <= 1452556800')
->groupBy(order_day, order_line.supplierID)
->orderBy(['availability.start' => SORT_ASC])
->all();
in this way you should obtain a row for supplierID (and order_day) avoinding the foreach on supplier
For getting the data in $results->num_bookings and order_day you need add
public $num_bookings;
public $order_day;
in your OrderLine model
I hope this is what you are looking for.
I have a table called 'orders' and it contains; id, order_total and time fields. 'time' is an integer and stores a unix timestamp...
orders
| id | order_total | time |
-------------------------------------
| 1 | 42.00 | 1443355834 |
| 2 | 13.00 | 1443460326 |
| 3 | 51.00 | 1443468094 |
| 4 | 16.00 | 1443477442 |
| 5 | 10.00 | 1443606966 |
| 6 | 53.00 | 1443608256 |
I want to able to display in a table using php the sum, of 'order_total' for each day for the previous 'x' amount of days (or weeks or months) so it will look something like this:
| Date | Order Total |
---------------------------
| 27/09/15 | 42.00 |
| 28/09/15 | 80.00 |
| 30/09/15 | 63.00 |
I have made a MYSQL query and a php loop that kind of works but being new to MYSQL I am probably over-complicating things and there must be an easier way to do this ? When I say kind of works, it will correctly sum and show the order_totals up until the current day but for some reason will combine the current day with the previous day.
Here is what I currently have:
$x = $interval;
$y = $x - 1;
while ($x > 0) {
$sql10 = "
SELECT id,
time,
SUM(order_total) as sum,
date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $x DAY), '%Y-%m-%d') as thedate
FROM $ordersTABLE
WHERE FROM_UNIXTIME(time) BETWEEN date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $x DAY),'%Y-%m-%d')
AND date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $y DAY),'%Y-%m-%d')";
$result10 = mysql_query ( $sql10, $cid ) or die ( "Couldn't execute query." );
while ( $row = mysql_fetch_array ( $result10) ) {
$order_total = $row ["order_total"];
$thedate = $row ["thedate"];
$sum = $row ["sum"];
$sum = number_format($sum,2);
$thedate = strtotime($thedate);
$thedate = date("d/m/y",$thedate);
print "<tr><td width=\"120\">$thedate</td><td>\$$sum</td></tr>";
}
$x--;
$y--;
}
(The string $now_time contains the current time as a Unix Timestamp hence the converting as the system time can not be changed and this contains the correct local time for the user)
Is there better way to do this ?
You can convert the timestamps into YYYY MM DD using FROM_UNIXTIME function and then select only the ones which are older enough thanks to the DATEDIFF function. Today's date is provided by CURDATE function.
First of all, the query which retrieves the totals for the orders older then the interval and reformats the date fields:
$q1 = "SELECT " . $ordersTABLE . ".order_total AS total, FROM_UNIXTIME(" . $ordersTABLE . ".time, '%Y-%m-%d') AS short_date FROM " . $ordersTABLE . " WHERE DATEDIFF(CURDATE(), short_date) > " . $intervalInDAYS;
Then, the one that sums up the totals of the day:
$q2 = "SELECT short_date AS day, SUM(total) AS total FROM (" . $q1 . ") GROUP BY short_date";
And then you perform your query stored in $q2 and all other operations you need to display the result.
Result from the query should be in form:
| day | total |
===========================
| 25/09/15 | 34.00 |
| 16/09/15 | 100.00 |
| 31/07/14 | 3.20 |
| ... | ... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am having an issue trying to pinpoint a problem I am having, the code below loops twice and gives me an output of Match11Match111Match11Match111 I am really not sure where the problem is but it should only loop once.
<?php
function generateTimeCard($conn, $employeeID){
// set current date
$date7 = date("m/d/y");
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date7);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
$date1 = date("m/d/y", $ts);
$date3 = date("l", $ts);
$$date3 = $date1;
$date2 = $date1;
$day[$i] = $date1;
$stmt = $conn->prepare('SELECT `employeeID`,`date`,`unitNumber`,`jobDescription`,`timeIn`,`timeOut`, `lunch`, TIMEDIFF(`timeOut`, `timeIn`)
AS `totalTime` FROM `timeRecords` WHERE `date`= :day AND `employeeID`= :employeeID ORDER BY date,id;');
$stmt->execute(array(':day'=>$day[$i], ':employeeID'=>$employeeID));
$dayOW = 1;
while($row = $stmt->fetch()) {
if ($row['lunch'] == "Yes"){
echo "Match";
} else{
echo "1";
}
$dayCurrent = $date3 . "Hours." . $dayOW;
$data[$dayCurrent] = $row['totalTime'];
$timeDay = $date3 . "." . $dayOW;
$unitNumber = $date3 . "UnitNumber." . $dayOW;
$description = $date3 . "Description." . $dayOW;
$data[$timeDay] = date("h:i A", strtotime($row['timeIn'])) . "/" . date("h:i A", strtotime($row['timeOut']));
$data[$unitNumber] = $row['unitNumber'];
$data[$description] = $row['jobDescription'];
$dayOW++;
}
$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalDay` FROM `timeRecords` WHERE `date` = :day
AND `employeeID` = :employeeID GROUP BY `employeeID`;');
$stmt->execute(array(':day'=>$date1, ':employeeID'=>$employeeID));
$row = $stmt->fetch();
$totalDay = "Total" . $date3;
$data[$totalDay] = $row['totalDay'];
}
$data['Week']= $Sunday . " - " . $Saturday;
return $data;
}
?>
My database looks like this
+----+------------+----------+--------+----------------------------+-------------+------------+-----------+---------+-------+
| id | employeeID | date | timeIn | jobDescription | equipType | unitNumber | unitHours | timeOut | lunch |
+----+------------+----------+--------+----------------------------+-------------+------------+-----------+---------+-------+
| 1 | 1 | 01/20/13 | 6:00 | Worked in RockPort | Excavator | 01E | 7238 | 17:13 | Yes |
| 2 | 1 | 01/21/13 | 6:00 | Worked in Jefferson | Excavator | 01E | 7238 | 17:17 | |
| 3 | 1 | 01/22/13 | 6:00 | Worked in Jefferson | Excavator | 02E | 7238 | 17:30 | |
| 4 | 1 | 01/23/13 | 6:00 | Worked in Whispering Creek | Skid Loader | 32SL | 2338 | 18:30 | Yes |
| 5 | 1 | 01/24/13 | 8:00 | Worked in Hubbard | Scraper | 54C | 9638 | 11:30 | |
| 6 | 1 | 01/25/13 | 8:00 | Worked in Jefferson | Dozer | 4D | 941 | 19:30 | |
| 7 | 1 | 01/26/13 | 8:00 | Pushed Snow | Loader | 950H | 342 | 20:30 | |
+----+------------+----------+--------+----------------------------+-------------+------------+-----------+---------+-------+
By default, PDO fetches with index and column-name keys. So there are "duplicate" values. You want to change the fetch mode to FETCH_NUM (only index keys) ($stmt->fetch(PDO::FETCH_NUM)) so that values don't appear under two mappings. http://php.net/manual/en/pdostatement.fetch.php