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
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 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
I have a table like this:
// Times
+----+-------------+
| id | timestamp | // echo date('d/m/Y', $time)
+----+-------------+
| 1 | 1448460315 | // 25/11/2015 -- today
| 2 | 1428440265 | // 07/04/2015
| 3 | 1418160365 | // 09/12/2014
| 4 | 1448460215 | // 25/11/2015 -- today
| 5 | 1438440265 | // 01/08/2015
| 6 | 1438340265 | // 31/07/2015
| 7 | 1438437265 | // 01/08/2015
| 8 | 1448370315 | // 24/11/2015 -- yesterday
| 9 | 1148370315 | // 23/05/2006
| 10 | 1447870315 | // 18/11/2015 -- last week ({11-18}/11/2015)
+----+-------------+
Note: All those number in timestamp column are made of time() function using PHP.
Now I want to know, how can I select all rows which are today Or all rows which are yesterday, or last week?* (it should be noted, in MySQL NOW() is the same with time()).*
For example:
// Times - Today
+----+-------------+
| id | timestamp | // echo date('d/m/Y', $time)
+----+-------------+
| 1 | 1448460315 | // 25/11/2015 -- today
| 4 | 1448460215 | // 25/11/2015 -- today
+----+-------------+
You would need to use the MySQL BETWEEN function
use PHP to get the timestamp from midnight of day to 11:59:59 of day
date_default_timezone_set('America/Chicago');
$day_begins = strtotime(date('Y-m-d 00:00:00', strtotime('today')));
$day_ends = strtotime(date('Y-m-d 11:59:59', strtotime('today')));
-- sql code will look like
SELECT id FROM table WHERE `timestamp` BETWEEN ($day_begins AND $day_ends)
With something like:
SELECT
id,
timestamp
FROM
table
WHERE
DATE_FORMAT(FROM_UNIXTIME(`timestamp`), '%y-%m-%d') = (DATE_FORMAT(NOW(), '%y-%m-%d') - INTERVAL 1 DAY)
I'm trying to enter events that occur over the same interval (Weekly, Bi-Monthly, Quarterly, Yearly). The script I'm showing is that of monthly..(If I can get that right, I can make an adaptation for the other intervals).
Events are entered along with the correct Week Number in which they occur.. But the following problem occur:
--- How can I make sure that months that has less than 31 days do not have events entered for them ?
----- If an event occurs on every 1st and 3rd friday (or whichever one), or last thursday of the month. How can I tweak the script below do do that.
Thank you.
A Sample of what I'm getting from mysql, when I insert...
+----+------+------+------------------+-----------+------------+----------+
| day| month| year | eventname | eventtime | eventplace | eventweek|
+----+------+------+------------------+-----------+------------+-----------
| 1 | 2 | 2011 | Social Gathering | 12PM | Room | 05 |
| 8 | 2 | 2011 | Social Gathering | 12PM | Room | 06 |
| 15| 2 | 2011 | Social Gathering | 12PM | Room | 07 |
| 22| 2 | 2011 | Social Gathering | 12PM | Room | 08 |
| 29| 2 | 2011 | Social Gathering | 12PM | Room | 09 |
+----+------+------+------------------+-----------+------------+----------+
PHP Code
<?php
if(isset($_POST['myform'])){
$day = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31');
$month = array('1','2','3','4','5','6','7','8','9','10','11','12');
$year = array('2011', '2012','2013', '2014', '2015', '2016');
$startday = mysql_real_escape_string($_POST['day']);
$eventplace = mysql_real_escape_string($_POST['eventplace']);
$eventname = mysql_real_escape_string($_POST['eventname']);
$eventtime = mysql_real_escape_string($_POST['eventtime']);
for($i=0; $i<count($year); $i++){
for($j=0; $j<count($month); $j++){
for($k=$startday; $k<count($day); $k = $k + 7){
$date = mktime(0,0,0,$month[$j],$k,$year[$i]);
$week = date('W', $date) ;
$query = mysql_query(" INSERT INTO caldemo(day, month, year, eventname, eventtime, eventplace, eventweek)
VALUES ('".intval($k)."', '".intval($month[$j])."', '".intval($year[$i])."', '".$eventname."', '".$eventtime."', '".$eventplace."', '".intval($week)."' )")or die(mysql_error()) ;
}
}
}
}
?>
Simple php solution:
function setDatePeriod($months=1, $date='')
{
if(!$date) $date = date('Y-m-d');
$d = new DateTime( $date );
$d->modify( "+{$months} months" );
return $d->format('Y-m-d');
}
echo setDatePeriod(3);
i need help creating a count down timer in php.
the problem is that i want to store an INT in my database which is going to be seconds,
and this int is going to be added to current time to represent the future time.
now if i try to subtract the current time from future time to show how many seconds remaining, am getting wrong date.
here is my schema
mysql> desc buildings;
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| level | int(2) | YES | | NULL | |
| created | int(11) | NO | | NULL | |
| finished | int(11) | YES | | NULL | |
| player_id | int(11) | YES | MUL | NULL | |
| position | int(2) | YES | | NULL | |
+-----------+-------------+------+-----+---------+----------------+
and heres the code to check
//starting session;
//connecting to database;
$query = "select created, finished from buildings where id = 1";
$query = mysql_query($query) or die ("could not query ".mysql_error() );
while($row = mysql_fetch_assoc($query))
{
$created = $row['created'];
$finished = $row['finished'];
}
$CurrentTime = time();
$status = $finished - $CurrentTime;
$realstatus = date("H:i:s",$status);
if($status > 0)
{
echo "under construction, still ".$realstatus." to finsih";
}else
{
die("construction complete");
}
//echo $created."".$finished;
?>
any help will be greatly appreciated.
Can't offer much of an answer without seeing your code, but maybe this will provide some insight:
<?php
$fmt = 'Y-m-d H:i.s'; // date formatting
$now = time(); // current time
$offset = 600; // future offset
$future = strtotime('+' . $offset . ' seconds'); // future time using relative time
$timeleft = $future - $now; // time left in seconds
// echo results
echo 'Current Time: ' . date($fmt, $now) . PHP_EOL;
echo 'Event Time: ' . date($fmt, $future) . PHP_EOL;
echo 'Time Until Event: ' . $timeleft . ' seconds' . PHP_EOL;
?>
Output:
Current Time: 2011-05-03 12:00.15
Event Time: 2011-05-03 12:10.15
Time Until Event: 600 seconds
Your problem is that you are subtracting two timestamps and format the result as a date. The result is not a date, it´s an interval between two dates.
If you want to know how many hours / minutes / seconds are remaining, you just have to divide your result $status through 3600 / 60 / 1 (divide for hours and take the remainder to divide for minutes etc.).