PHP Loop Month Row, with Weekly columns - php

I'm setting up a report with the following columns, Month, Teller, Week 1, Week 2, week 3, Week 4, and Week 5 and a Total collection of the Month.
I have difficulties to sum up the amount from the database for each week of a row.
Maybe if anyone can help me how to show the list of dates within each week of a month, could be helpfull!
That will show a monthly weekly collection of tellers.
I wan't to sum the collection from the database weekly from the month every tellers.
Database Table
My Code.
if($teller_cnt > 0) {
$new_start_week = 0;
$weeks_num = 5;
for($m = 1; $m<=12; $m++) {
$weeks_num = weeks_num($m, $year);
$num_of_weeks = $weeks_num;
$monthname = date_formating($m, '!m', 'F');
$total_per_month = 0;
$min_1 = 0;
if($m > 1) {
if($num_of_weeks == 4) {
$new_start_week = ($new_start_week + $weeks_num) + 1;
$weeks_num = ($weeks_num + $new_start_week);
$msg = '<span class="label label-danger">4 Months</span>';
}else{
$new_start_week = ($new_start_week + $weeks_num);
$weeks_num = ($weeks_num + $new_start_week);
$msg = '<span class="label label-info">5 Montsh</span>';
$min_1 = -1;
}
}else{
if($num_of_weeks == 4) {
$msg = '<span class="label label-danger">4 Months</span>';
}else{
$msg = '<span class="label label-info">5 Montsh</span>';
}
}
if(weeks_num(($m-1), $year)==4) {
$weeks_num = $weeks_num - 1;
$new_start_week = $new_start_week - 1;
}
echo '<tr>';
echo '<td rowspan="'.($teller_cnt+1).'">';
echo $monthname.' <br>';
//echo 'Num of Weeks per month: '.$num_of_weeks. ' <br> ';
//echo 'Start Of Week Num: ' . $new_start_week;
//echo $msg . '<br>';
echo '</td>';
echo '</tr>';
foreach ($qry_pay_tellers->result() as $row) {
$qry_total_payapplied = $this->db->query("SELECT SUM(amt) + SUM(intrst) AS amt FROM payapplied WHERE teller = {$row->teller} AND YEAR(tdate) = $year AND MONTH(tdate) = $m")->row();
$total_teller_amt = ($qry_total_payapplied) ? $qry_total_payapplied->amt : 0;
echo '<tr>';
echo '<td>' . $row->teller . '</td>';
/*
$firstDayOfMonth = new \DateTime("1st $monthname");
$lastDayOfMonth = new \DateTime($firstDayOfMonth->format('t M Y'));
$oneDay = new DateInterval('P1D');
$period = new \DatePeriod($firstDayOfMonth, $oneDay, $lastDayOfMonth->add($oneDay));
*/
$days_arr = array();
$begin = new DateTime('2019-01-01');
$end = new DateTime('2019-12-31');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $date)
{
$dates = $date->format('Y-m-d');
$week_num = $this->db->query("SELECT WEEK('$dates', 'Monday') AS weeknum;")->row();
$days_arr[$week_num->weeknum][] = array('dayname' => $date->format('D'), 'date' => $dates);
// echo $dates . ' - ' . $week_num->weeknum . '<br>';
}
for($w = $new_start_week; $w < $weeks_num; $w++) {
echo '<td>';
/*
echo $w . '<br>';
foreach($days_arr[$w] as $wrow) {
echo $wrow['date'] . '<br>';
}
*/
echo '</td>';
}
//echo '<td class="number">'.number_format($total_teller_amt, 2).'</td>';
if($num_of_weeks > 4) {
echo '<td class="number">'.number_format($total_teller_amt, 2).'</td>';
}else{
echo '<td colspan="2" class="number">'.number_format($total_teller_amt, 2).'</td>';
}
echo '</tr>';
$total_per_month += $total_teller_amt;
}
echo '<tr>';
echo '<td class="number" colspan="8">'.number_format($total_per_month, 2).'</td>';
echo '</tr>';
}
}

My Solution.
Thanks anyway.
Created Array of Days from Jan to December and identify its week numbers.
$begin = new DateTime( '2019-01-01' );
$end = new DateTime( '2019-12-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
$dates_arr = array();
foreach($daterange as $date){
$dates = $date->format('Y-m-d');
$week_num = $this->db->query("SELECT WEEK('$dates', 'Monday') AS weeknum;")->row();
$month_n = (int)$date->format('m');
$dates_arr[$month_n][] = array(
'week' => $week_num->weeknum,
'dayname' => $date->format('D'),
'dates' => $date->format('Y-m-d')
);
}
Then Create a table to index month and week and query loop tellers
echo '<div class="row">';
echo '<div class="col-md-12">';
echo '<table class="table table-hover table-condensed table-bordered table-striped table-small">';
echo '<thead>';
echo '<th>Month</th>';
echo '<th>Teller</th>';
echo '<th>Week 1</th>';
echo '<th>Week 2</th>';
echo '<th>Week 3</th>';
echo '<th>Week 4</th>';
echo '<th>Week 5</th>';
echo '<th></th>';
echo '<th>Total</th>';
echo '</thead>';
echo '<tbody>';
for($month = 1; $month<=12; $month++) {
$total_per_month = 0;
$weeks_r = array();
foreach ($dates_arr[$month] as $rw) {
$weeks_r[] = $rw['week'];
}
$u_week_r = array_unique($weeks_r);
$monthname = date_formating($month, '!m', 'F');
echo '<tr>';
echo '<td rowspan="' . ($teller_cnt + 1) . '">';
echo $monthname . ' <br>';
echo '</td>';
echo '</tr>';
$total_teller_amt = 0;
foreach ($qry_pay_tellers->result() as $row) {
echo '<tr>';
echo '<td>' . $row->teller . '</td>';
foreach ($u_week_r as $wrow) {
echo '<td class="number" style="font-size: 8px;">';
$dates_arr_s = array();
foreach ($dates_arr[$month] as $drow) {
if ($drow['week'] == $wrow) {
if(isWeekend($drow['dates']) == false) {
$dates_arr_s[] = $drow['dates'];
$qry_pay_applied_wamt = $this->db->query("
SELECT SUM(amt) + SUM(intrst) AS amt FROM payapplied WHERE teller = {$row->teller} AND CAST(tdate AS DATE) = '{$drow['dates']}'
")
->row();
$amt_per_week = ($qry_pay_applied_wamt) ? $qry_pay_applied_wamt->amt : 0;
$total_teller_amt += $amt_per_week;
echo '<span style="float: left !important;">'.$drow['dates'] . ' - ' . $drow['dayname'] . '</span><span class="pull-right">'.number_format($amt_per_week, 2).'</span><br>';
}
}
}
echo '</td>';
}
if(count($u_week_r) > 4) {
if(count($u_week_r) > 5) {
echo '<td class="number">' . number_format($total_teller_amt, 2) . '</td>';
}else{
echo '<td colspan="2" class="number">' . number_format($total_teller_amt, 2) . '</td>';
}
} else {
echo '<td colspan="3" class="number">' . number_format($total_teller_amt, 2) . '</td>';
}
echo '</tr>';
$total_per_month += $total_teller_amt;
}
echo '<tr>';
echo '<td class="number" colspan="9">'.number_format($total_per_month, 2).'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';
echo '</div>';

Related

PHP while to populate table with function to repeat data calculation

In a contract management tool I'm trying to populate a table from a PHP query.
The function is working properly until I use it in the while to calculate several dates during the same while loop.
FUNCTION CODE:
function calculo_data($data_calculo){
if($data_calculo == 0 ){
$result_datas = "NÂO aplicavel ";
echo $result_datas;
} else {
$hoje = date_create();
$data_calculo_date = date_create($data_calculo);
$diff = date_diff( $hoje, $data_calculo_date );
$meses = (($diff->format('%y')*12)+$diff->format('%m'));
$dias = $diff->days;
if($data_calculo_date < $hoje){
$result_datas = "não aplicavel ";
echo $result_datas;
} elseif($meses >=1 ) {
$result_datas = $meses . " meses ";
echo $result_datas;
} else {
$result_datas = $dias . " dias ";
echo $result_datas;
};
;
};
};
TABLE CODE:
while ($row_detalhes = mysqli_fetch_assoc($result_listagem_contratos)){
$listagem_cliente_ref = $row_detalhes['PkContrato'];
$listagem_cliente_cliente = $row_detalhes['ClienteNome'];
$listagem_cliente_inicio = $row_detalhes['ContratoDataInicio'];
$listagem_cliente_fim = $row_detalhes['ContratoDataFim'];
$listagem_cliente_senhorio = $row_detalhes['ContratoPreAvisoSenhorio'];
$listagem_cliente_inquilino = $row_detalhes['ContratoPreAvisoInquilino'];
$listagem_cliente_break = $row_detalhes['ContratoDataBreak'];
echo '<tr>';
echo '<td>' . $listagem_cliente_ref .'</td>';
echo '<td>' . $listagem_cliente_cliente .'</td>';
echo '<td>' . $listagem_cliente_inicio .'</td>';
echo '<td>' . $listagem_cliente_fim .' ( ' . calculo_data($listagem_cliente_fim) . ' )</td>';
echo '<td>' . $listagem_cliente_senhorio .' ( ' .calculo_data($listagem_cliente_senhorio) . ' )</td>';
echo '<td>' . $listagem_cliente_inquilino .' ( ' . calculo_data($listagem_cliente_inquilino) . ' )</td>';
echo '<td>' . $listagem_cliente_break .' ( ' . calculo_data($listagem_cliente_break) . ' )</td>';
echo '<td><a href="detalhe_contrato.php?id='. $listagem_cliente_ref . '">
<span class="glyphicon glyphicon-file" style="color:black"></span>
</a></td<>';
The result is the table showing at least part of the results but in the wrong position as in the picture!
It's because you echo directly in the function. It should return the values, not echo them:
function calculo_data($data_calculo){
if($data_calculo == 0 ){
$result_datas = "NÂO aplicavel ";
return $result_datas;
} else {
$hoje = date_create();
$data_calculo_date = date_create($data_calculo);
$diff = date_diff( $hoje, $data_calculo_date );
$meses = (($diff->format('%y')*12)+$diff->format('%m'));
$dias = $diff->days;
if($data_calculo_date < $hoje){
$result_datas = "não aplicavel ";
return $result_datas;
} elseif($meses >=1 ) {
$result_datas = $meses . " meses ";
return $result_datas;
} else {
$result_datas = $dias . " dias ";
return $result_datas;
}
}
}
There were also some ; too much that I removed.

Colspan breaks table

ORIGINAL
I have a page that displays all the company boardrooms and bookings for a certain day. It looks like this:
As you can see, some of the rows create an extra <td>
Here is the code that generates the table:
<table celladding="0" cellspacing="0" class="table table-bordered col-xs-12">
<thead>
<tr style="background-color:#FFF">
<?php
$width = (100 / (count($boardrooms->toArray()) + 1));
$width = 100 / 7;
?>
<th style="border-right:none; width:<?= $width; ?>%; border-bottom: none;">Boardroom</th>
<?php
foreach($boardrooms as $boardroom) { ?>
<th rowspan="2" style="width:<?= $width; ?>%"><?php echo $boardroom ?></th>
<?php } ?>
</tr>
<tr>
<th>Time</th>
</tr>
</thead>
<?php
$writerow = false;
for($hour = 8; $hour < 17; $hour++) {
for($minute = 0; $minute < 4; $minute++) {
echo '<tr><td>' . $hour . ':' . str_pad(($minute*15),2,"0") . '</td>';
foreach($boardrooms as $boardroom) {
foreach($boardroomBookings as $booking) {
if(date('H:i',strtotime($hour . ':' . str_pad(($minute*15),2,"0"))) >= date('H:i',strtotime($booking->start_time)) &&
date('H:i',strtotime($hour . ':' . str_pad(($minute*15),2,"0"))) < date('H:i',strtotime($booking->end_time)) &&
$boardroom == $booking->boardroom->name && (empty($boardroomWritten[$booking->id]) || !$boardroomWritten[$booking->id])) {
$boardroomWritten[$booking->id] = true;
$writerow = true;
$rowspan = (strtotime($booking->end_time) - strtotime($booking->start_time))/900;
echo '<td style="background-color:#8cc63f; border-bottom:none" rowspan="' . $rowspan . '">' . $this->Html->link($booking->name, array('action' => 'view', $booking->id)) . '</td>';
break;
} else {
$writerow = false;
}
}
if(!$writerow) {
echo '<td></td>';
}
}
echo '</tr>';
}
}
?>
</table>
How can I prevent the rows from displaying the extra empty cell on rows that have a booking?
EDIT
Here's the same table with black borders:
And what it looks like without a booking:
And what it should look like with a booking:
If you don't have a booking you need to insert a td pair unless you are inside a colspan:
<?php
for($hour = 8; $hour < 17; $hour++) {
for($minute = 0; $minute < 4; $minute++) {
$bookTime = date('H:i ',strtotime($hour . ':' . str_pad(($minute*15),2,"0"))) ;
echo '<tr><td>' . $bookTime . '</td>';
foreach($boardrooms as $boardroom) {
$hasBooking = false;
foreach($boardroomBookings as $booking) {
$sTime = strtotime($booking->start_time) ;
$eTime = strtotime($booking->end_time) ;
$startTime = date('H:i',$sTime);
$endTime = date('H:i', $eTime) ;
if($bookTime >= $startTime && $bookTime < $endTime && $boardroom == $booking->boardroom->name) {
$hasBooking = true;
if(empty($boardroomWritten[$booking->id]) || !$boardroomWritten[$booking->id]) {
$boardroomWritten[$booking->id] = true;
$rowspan = ($eTime - $sTime)/900 ;
echo '<td style="background-color:#8cc63f; border:1px black solid" rowspan="' . $rowspan . '">' . "somelink" . '</td>';
break;
}
}
}
if (!$hasBooking) {
echo "<td></td>" ;
}
}
echo '</tr>';
}
}

Incorrect output when calculating totals

I have a web page where i am able to export a .csv file that is readable on excel. The invoice pulls the data from my database to calculate the total and grand total using the following columns:
quantity, packing_price, courier_price
I have noticed that my code doesn't output the correct answer when the prices contains a '£' sound in front of it. Is there a way that i could make this work for both number and currency data types?
CODE:
$output2= "";
$sql2 = mysql_query("
SELECT j.date
, j.order_ref
, j.quantity
, j.packing_price
, j.dispatch_type
, j.courier_price
FROM Jobs j
WHERE j.order_type = 'Retail International'
AND j.confirmed = 'Yes';
");
$columns_total2 = mysql_num_fields($sql2);
$total3 = "Total";
for ($i = 0; $i < $columns_total2; $i++)
{
$heading2 = mysql_field_name($sql2, $i);
$output2 .= '"'.$heading2.'",';
}
$output2 .= $total3;
$output2 .="\n";
$sum2 = 0;
while ($row = mysql_fetch_array($sql2)) {
for ($i = 0; $i < $columns_total2; $i++) {
$output2 .='"'.$row["$i"].'",';
}
$qty2 = $row['quantity'];
$pack_price2 = $row['packing_price'];
$dispatch2 = $row['courier_price'];
$total2 = (($qty2*$pack_price2) + $dispatch2);
$total3 = $total2*1.2;
$output2 .= $total3;
$sum2 += $total3; // Add to overall total
$output2 .="\n";
}
Output:
http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-07-03at113133_zpsbcc09900.png
Use this Code....
$output= "<table border='1' width='60%'><tr>";
$sql = " SELECT j.date ,
j.order_ref ,
j.quantity ,
j.packing_price ,
j.dispatch_type ,
j.courier_price
FROM Jobs j
WHERE j.order_type = 'Retail International'
AND j.confirmed = 'Yes' ";
$query = mysql_query($sql);
$total_columns = mysql_num_fields($query);
for ($i = 0; $i < $total_columns; $i++){
$heading = mysql_field_name($query, $i);
$output .= '<td>' . $heading . '</td>';
if(($i+1) == $total_columns) $output .= '<td>Total</td></tr>';
}
while ($row = mysql_fetch_array($query)) {
$total_price = 0;
$total_price =( ( $row['quantity'] * $row['packing_price'] ) +
$row['courier_price'] );
$total_price = $total_price * 1.2;
$timestamp = DateTime::createFromFormat('Y-m-d h:i:s',
$row['date'])->getTimestamp();
$output .= '<tr>';
$output .= '<td>' . date("d/m/Y", $timestamp) . '</td>';
$output .= '<tr>';
$output .= '<td>' . date("d/m/Y", strtotime($row['date']) . '</td>';
$output .= '<td>' . $row['order_ref'] . '</td>';
$output .= '<td>' . $row['quantity']. '</td>';
$output .= '<td>' . $row['packing_price'] . '</td>';
$output .= '<td>' . $row['dispatch_type'] . '</td>';
$output .= '<td>' . $row['courier_price'] . '</td>';
$output .= '<td>' . number_format($total_price, 2) . '</td>';
$output .= '</tr>';
}
$output .= "</table>";
echo '<br>' . $output;

Netbeans says PHP function has too many lines

I have a function and netbeans is saying I can only have 20 lines in my code.
Why is this and how could I fix this. I have another function with the same problem. Dreamweaver doesn't say anything so I don't know if this is a big problem.
my code:
function dispalyEvent($weekNr, $week, $year){
echo "<p>";
$gendate = new DateTime();
$gendate->setISODate($year,$week,$weekNr);
$month = $gendate->format('m');
$day = $gendate->format('d');
$event_query = mysql_query("SELECT * FROM calendar ORDER BY starttime");
while($event = mysql_fetch_array($event_query)) {
$startYear = $event['startyear'];
$startMonth = $event['startmonth'];
$startDay = $event['startdate'];
$endYear = $event['endyear'];
$endMonth = $event['endmonth'];
$endDay = $event['enddate'];
$period = new DatePeriod(
new DateTime($startYear.$startMonth.$startDay),
new DateInterval('P1D'),
new DateTime($endYear.$endMonth.$endDay +1)
);
$currentDate = $year."-".$month."-".$day;
foreach ($period as $savedDate) {
if ($currentDate == $savedDate->format('Y-m-d')){
if ($event['Approved'] == "Approved"){
echo "</p>";
echo "<p>";
if ($event['ad']) {
echo "<img src='images/".$event['ad']."' alt='event-ad' width='300' height='100' />";
} else { echo " "; }
echo "</p>";
echo "<p> </p>";
echo "<div class='toggleLink' style='cursor: pointer; color: #333;'>";
echo $event['starttime']." ".$event['title'];
echo "</p>";
echo "</div>";
echo " <div class='toggle'>";
echo "<p class='toggleLink'>";
echo "(".$event['starttime']."-".$event['endtime'].") ".$event['location']." - ".$event['address']." - Admission Price: $".$event['price']."<br>".$event['description'];
echo "</div>";
}}}}
echo "</p>";
}
?>

PHP getting days of a month for a database

I'm making a calender planner with php/css/javascript/html.
I am trying to set each day of the month a class which is "day". I tried using the following:
**PHP CODE**
error_reporting(E_ALL);
ini_set('display_errors', '1');
include "scripts/connect_to_mysql.php";
$jobNameValue ='';
$monthDays = '';
$monthname = '';
$days = '';
//getting values for job names
$sql_job_name = mysql_query("SELECT * FROM jobs");
$num_job_name = mysql_num_rows($sql_job_name);
if($num_job_name >0) {
while ($row = mysql_fetch_array($sql_job_name)) {
$job_name = $row["job_name"];
$job_short_name = $row["job_short_name"];
$jobNameValue .= '<option value="' . $job_short_name . '">' . $job_name . '</option>';
}
} else {
$jobNameValue .= '<option value="NULL">No job listed</option>';
}
//getting values for months days
$sql_month_days = mysql_query("SELECT * FROM months");
$num_month_days = mysql_num_rows($sql_month_days);
if($sql_month_days > 0) {
while($row = mysql_fetch_array($sql_month_days)) {
$month_id = $row["id"];
$name = $row["name"];
$num_days = $row["num_days"];if($num_days === "31") {
for($i=1; $i <=31; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "30") {
for($i=1; $i <=30; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "29") {
for($i=1; $i <=29; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
}
}
}
$monthDays .= '<div id="monthContainer">
<span class="monthName">'. $name .'</span>
<div class="monthDaysContainter">
'. $days.'
</div>
</div>';
}
}
**HTML CODE**
<div id="container">
<div ="newJob">
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="newJobForm">
<label for="jobName">Job Name:</label>
<select id="jobName">
<?php echo $jobNameValue; ?>
</select>
<input type="date">
<input type="submit" id="submit">
</form>
</div>
<div id="calander">
<?php echo $monthDays; ?>
</div>
</div>
It does not work correctly, it kept duplicating every month and I am not sure how to correctly right the php to achieve what was intended.
I am only a beginner at php so I am not good at the moment
Could anyone help me with this?
If there any more information you need, please don't hesitate to ask.
Thank you in advance!
Chris
Try just doing this and seeing if that fixes it, you don't need all of those if statements
for($i=1; $i <= $num_days; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
do not use ===,use ==,maybe your $num_days is integer
Your problem is that you are creating the whole thing in the while loop, so the days that are appended from the last call are also appended to the next output.
$tmpArray = array();
if($sql_month_days > 0) {
while($row = mysql_fetch_array($sql_month_days)) {
array_push($tmpArray, $row);
}
}
foreach($tmpArray as $k){
$monthDays .= '<div id="monthContainer"><span class="monthName">'. $k['name'] .'</span><div class="monthDaysContainter">'. calNumDays($k['num_days']).'</div></div>';
}
Update
Should you wish to keep what you already have
if($num_days === "31") {
$days = '';
for($i=1; $i <=31; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "30") {
$days = '';
for($i=1; $i <=30; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "29") {
$days = '';
for($i=1; $i <=29; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
}
}
}
You only really to need to reinitialize the $days before each for after the if

Categories