cannot match date day based on array data on database on php - php

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.

Related

calculating time attendance in PHP MySQL

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

Yii2 - Query count per day to ActiveRecord

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.

Change content of table according to week number

I am working on a script for a drivers license website, and I need to make a calendar like table for the students, so they can see when they have which lesson.
Right now we are updating the table manually, but I would like to make a script so it can do it automatically.
The table looks like this: (By the way, its a HTML table).
+----------+--------+---------+-----------+----------+--------+
| Week Nr. | Monday | Tuesday | Wednesday | Thursday | Friday |
+----------+--------+---------+-----------+----------+--------+
| 17 | 14 | 1 | 16 | 2 | |
+----------+--------+---------+-----------+----------+--------+
| 18 | 4 | 1 | 6 | | |
+----------+--------+---------+-----------+----------+--------+
| 19 | 8 | 1 | 11 | | |
+----------+--------+---------+-----------+----------+--------+
| 20 | 14 | 1 | 16 | 2 | |
+----------+--------+---------+-----------+----------+--------+
Lets say its this week (Week 17), it has its own set of lessons for every day, except Friday, which is the same for every week. Then it is the week after, which has its own set of lessons, and then it is 3 weeks after, which again has its own set of lessons. Then the 4th week, it start all over, with the same set as week 17, because its a 3 week program, over and over again.
What i want to do is that it automatically updates the table, so it shows the current week number. Then let us say that it is next week now, the table should have automatically update it self to show the current week and its set of lesson numbers.
The numbers under the column "Week Nr." are the week numbers, and the numbers under the day names are the lesson numbers.
So next week it should look like this:
+----------+--------+---------+-----------+----------+--------+
| Week Nr. | Monday | Tuesday | Wednesday | Thursday | Friday |
+----------+--------+---------+-----------+----------+--------+
| 18 | 4 | 1 | 6 | | |
+----------+--------+---------+-----------+----------+--------+
| 19 | 8 | 1 | 11 | | |
+----------+--------+---------+-----------+----------+--------+
| 20 | 14 | 1 | 16 | 2 | |
+----------+--------+---------+-----------+----------+--------+
| 21 | 4 | 1 | 6 | | |
+----------+--------+---------+-----------+----------+--------+
Is there anybody who could give me a hint on how to do that with PHP. I have tried everything I knkw, but I just cant get it right.
This is not exactly what you want, but it could be a good starting point. Just modify it to print out the HTML tags.
//Set a counter for the lessons
$j = 0;
//Loop through the weeks of the year
for ($i = 1; $i <= 52; $i++) {
echo "Week: ".$i."<br>";
echo "This weeks lessons: " . $j."<br>";
//Incrase counter
$j++;
if ($j % 3 === 0) {
//Reset counter if need
echo "<hr>";
$j = 0;
}
}

Coordinates from MySQL to HTML table (PHP, PDO, MySQL)

I am creating game which uses MySQL database to create "playing field".
In my MySQL table I have two columns pointX and pointY, both INT. I could also use POINT, but in my case these two columns are better solution.
| id | pointX | pointY | player | game |
|----|--------|--------|--------|------|
| 1 | -2 | 1 | 7 | 10 |
| 2 | -3 | 2 | 5 | 10 |
| 3 | 2 | -2 | 2 | 10 |
| 4 | -2 | -1 | 1 | 10 |
I should produce HTML table from this MySQL table. Something like this, but with no coordinateheaders (below those are only for easier understanding):
|-----|----|----|----|----|----|----|
| Y/X | -3 | -2 | -1 | 0 | 1 | 2 |
|-----|----|----|----|----|----|----|
| -2 | | | | | | 2 |
|-----|----|----|----|----|----|----|
| -1 | | 1 | | | | |
|-----|----|----|----|----|----|----|
| 0 | | | | | | |
|-----|----|----|----|----|----|----|
| 1 | | 7 | | | | |
|-----|----|----|----|----|----|----|
| 2 | 5 | | | | | |
|-----|----|----|----|----|----|----|
Plus.. every <td> should have attribute data-cell, which includes coordinates, as example data-cell="-2x-1".
What is the best way to get started?
$rng = $dbh->prepare('
SELECT MIN(pointX) AS minX, MIN(pointY) AS minY,
MAX(pointX) AS maxX, MAX(pointY) AS maxY
FROM field
WHERE game = ?
LOCK IN SHARE MODE
');
$qry = $dbh->prepare('
SELECT pointX, pointY, player
FROM field
WHERE game = ?
ORDER BY pointX, pointY
');
$dbh->beginTransaction();
$rng->execute([$game_id]);
$qry->execute([$game_id]);
$dbh->rollBack();
$limits = $rng->fetch();
$player = $qry->fetch();
echo '<table>';
for ($y = $limits['minY']; $y <= $limits['maxY']; $y++) {
echo '<tr>';
for ($x = $limits['minX']; $x <= $limits['maxX']; $x++) {
printf('<td data-cell="%dx%+dy">', $x, $y);
if ($player and $player['pointX'] == $x and $player['pointY'] == $y) {
echo htmlentities($player['player']);
$player = $qry->fetch();
} else {
echo ' ';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
It looks like you are already off to a good start. Assuming the number of cells for X and Y as $xcells and $ycells, the next step I would take is to build your table like so:
echo "<table>";
for ($i = -3; $i < $ycells; i++) {
echo "<tr>";
for ($j = -3; $j < $xcells; j++) {
echo "<td data-cell='" . $i . "y" . $j . "x'>";
}
echo "</tr>";
}
echo "</table>";

PHP: Fill fixed size chart with mysql data

I have a table chart. Lets say 5 by 5. I run a loop such as
<table>
<tbody>
<?php for ($i = 0; $i < 5; $i += 5) {
echo "<tr>
<td>one box</td>
<td>one two</td>
<td>one three</td>
<td>one four</td>
<tr>";
}?>
</tbody>
</table>
It creates a table such as
| | | | | |
-------------------------------------
| | | | | |
-------------------------------------
| | | | | |
-------------------------------------
| | | | | |
-------------------------------------
| | | | | |
-------------------------------------
Now I have mysql data I load for my purposes and I need it to put the data in respectively so the table looks like
| | | | | |
-------------------------------------
| | | | | |
-------------------------------------
| | Res 1| | | |
-------------------------------------
| | | | Res 3| |
-------------------------------------
| |Res 4 | | | Res 2|
-------------------------------------
How would I do this? I have 50 results and need to fill the results into the correct column and row. I need to do some sort of if(results[0-50]['id'] == rowcolumnid) echo the results for the correct table while doing the for loop.
Edit: Here is my full code.
<table id="schedule">
<tbody>
<?php
$time = mktime(0, 0, 0, 1, 1);
for ($i = 28800; $i < 62200; $i += 1800) { ?>
<tr id="row<?php echo $i; ?>">
<td id="hour">
<?php
printf('%1$s',date('g:i a', $time + $i));
?>
</td>
<td id="sunday"></td>
<td id="monday"></td>
<td id="tuesday"></td>
<td id="thursday"></td>
<td id="friday"></td>
<td id="saturday"></td>
</tr>
<?php } ?>
</tbody>
</table>
My mysql results are in datetime format that I'm going to use to propogate the table.
Results:
ID| EVENT NAME | DATEOFEVENT
1 | event name | 2012-11-20 12:00:00
2 | event name | 2012-11-21 13:30:00
3 | event name | 2012-11-22 13:00:00
4 | event name | 2012-11-23 11:00:00
5 | event name | 2012-11-24 08:00:00
etc.
I can do a strtotime of the dates and a date command to match.
If you first fetch the data (or if it is sorted if you first fetch the first data), then you can just iterate over the data when you match the hour/time that you iterate over to draw the table.
As an example, I've chosen to display only one column that represents 5 hours (1-5) of which some can be matched. Those that are matched, are stored in an array and made available as an iterator (ArrayIterator):
$data = [3,5];
$datas = new ArrayIterator($data);
$datas->rewind();
Matched hours are represented with 1, unmatched ones with 0:
echo "+---+---+\n";
foreach(range(1, 5) as $hour)
{
if ($hasData = ($datas->valid() and $datas->current() === $hour)) {
$datas->next();
}
$hasData = (int) $hasData;
echo "| $hour | $hasData |\n";
echo "+---+---+\n";
};
Output:
+---+---+
| 1 | 0 |
+---+---+
| 2 | 0 |
+---+---+
| 3 | 1 |
+---+---+
| 4 | 0 |
+---+---+
| 5 | 1 |
+---+---+
This works perfectly if the data from the data is available as an iterator (often the case, for mysql_* you need to write you one) and if it is sorted.
Even this is only a single list here, for a table this works actually equally because a table is just a different form of representing the data.

Categories