Why last column of table starts printing outside table - php

I want to print a table of this week with the tasks you have to do each day, but for a certain reason the first value of the task column is printed above the table and the second value is shown in the first task cell. For this reason, the last cell of the last column is always empty. How do I fix this?
$weekdagen = ["maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag","zondag"];
//today
$vandaag = date("d-m-Y",time());
//day of week starting on Monday (-1)
$weekdag = date('w', strtotime($vandaag)) -1;
$i = 0;
//get first day of this week
$startWeek = date('Y-m-d', strtotime('-'.($weekdag).' days'));
$datum = $startWeek;
while($i<7)
{
print '<tr>
<td>'.$weekdagen[$i+1].'</td>
<td>'.$datum.'</td>
<td>' .printTasks($datum); '</td>
</tr>';
$i++;
$datum = date('Y-m-d', strtotime($datum.' +1 days'));
}
function printTasks($date) {
$sql = "SELECT taa_omschr FROM taken where taa_datum = '".$date."'";
$res = SQLexec($sql);
while($row = $res->fetch_assoc()) { print $row[taa_omschr] . '<br>'; }
}
I changed my SQL statement to $date - 1 day so the right task is shown next to the right date, but it doesn't solve the problem that the last cell is empty.

Related

Adding days to current date only once

I want to add particular days to current date. where days are taking from database field. It adds to the present date properly but at next day, date is going to update to the present date again.so how to keep date unchanged. It should take only once in PHP
$day= $cur["Days"];
if(($cur["Days"]) == 0){
$new = '';
} else {
$Date = date('20y-m-d');
$new = date("20y-m-d", strtotime($Date . ' + ' . $day . ' days'));
}
input if $day=1,$day+$new
output= jan19,this is the output of one row and my problem is it should remain as it is for this row but now for next day it is going to change to jan20 that should not happen

Add data if current day is equal to last day of the month ONCE every month

I want to update my data if the current date is equal to last day of the month leave variable will update +1 once every month only, but it seems that when I refresh the homepage it keeps on adding.
function get_leave() {
$current_date = date('d'); // current date
$lastDayOfMonth = date('t'); // last day of the month
$leave = 1;
$total_add_leave = 0;
$query = $this->db->query('SELECT total_leave,user_id FROM user');
foreach ($query->result_array() as $row) {
if($current_date == $lastDayOfMonth) { //if current day is equal to last day of the month ADD 1
$total_add_leave = $row['total_leave'] + $leave;
}
$this->db->set('total_leave',$total_add_leave);
$this->db->where('user_id', $row['user_id']);
$this->db->update('user');
}
}
You can do this as below:
$current_date = date("y-m-d");
$last_day_of_the_month = date("y-m-t", strtotime($current_date));
if($current_date == $last_day_of_the_month) {
$total_add_leave = $row['total_leave'] + 1;
// database updating query must be placed in this condition
}
With this function you will find last date of month "t gives you last date of month"
date("Y-m-t");
then compare with current date
if(date("Y-m-d") == date("Y-m-t"))
{
// write your logic here
}

Create a cumulative comparison table in PHP and MySql

I have a database table called payments which contains date,amount fields. I want to take values from amount field and SUM up all amounts by date and take the results to html table then output them like on the image.
I have created dates dynamically so that they will be equal nomatter which months example January its 1-31 and February its 1-31. Where there is a weekend or the date is invalid i want the value to be zero. What i want is like this table [table][1] [1]: http://i.stack.imgur.com/iMOl3.jpg
This is what i am getting [output][1][1]: http://i.stack.imgur.com/MJpyT.jpg
******NOTE***** I THINK MY SOLUTION IS NOT THE BEST SOLUTION TO MY PROBLEM. IF POSSIBLE JUST TAKE I VIEW ON THE PICTURE WHICH I WANT AND FIND ME THE BEST SOLUTION. I WANT TO BE HELPED IN EITHER STEPS TO ACHIEVE IT OR A SOLUTION
I know that i am using a depricated mysql synthax please ignore that and help on my problem.
<table border="1" align="center">
<?php
session_start();
include("connection/db_con.php");
$sym='-';
$d=array();
///Insert values of month for period selected into an array
$a = $_POST['dat'];
$b = $_POST['dat2'];
$mnth=array();
$m_nam=array();
$m_nm=array();
$m_nam[]="Day";
//////New way of getting months in format Y-m
$start = new DateTime($a);
$start->modify('first day of this month');
$end = new DateTime($b);
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
$mnth[]=$dt->format("Y-m");
$m_nam[]=date('F-Y', strtotime($dt->format("Y-m")));
$m_nm[]=date('M', strtotime($dt->format("Y-m")));
}
///////End of New way
echo "<tr bgcolor='#999999'>";
foreach ($m_nam as $m)
{
echo"<td>".$m."</td>";
}
echo"</tr>";
/////////End insert////////////////////////
$day=0;
for($x=1; $x<=31; $x++)
{
$day=$day+1;
echo"<tr>";
echo"<td>".$day."</td>";
$d=$sym.$x;
foreach($mnth as $mon)
{
$dat=$mon.$d;
$qry=mysql_query("SELECT SUM(amount) AS total_disb FROM payments where dat='$dat'")or die(mysql_error());
$row=mysql_fetch_assoc($qry);
$sum = $row['total_disb']+0;
echo"<td>".$sum."</td>";
}
echo"</tr>";
}
?>
</table>
Here's a rewrite of the code you provided, it's using dummy random data instead of DB and there is no logic for POST variables, but that you can replace with your code.
<?php
// session start, db connection goes here
echo '<table border="1" align="center">';
// Example of post vars
$start = new DateTime('2015-11-10');
$end = new DateTime('2016-02-28');
// Note: not sure why OP used modify here
$interval = new DateInterval('P1M');
$daterange = new DatePeriod($start, $interval, $end);
// Table Header row 1
echo '<tr><th>Day</th>';
foreach ($daterange as $date) {
echo '<th colspan="2">'.$date->format("F Y").'</th>';
}
echo '</tr>';
// Temporary month store
$months = array();
// Table Header row 2
echo '<tr style="background-color:#22bb22;"><th></th>';
foreach ($daterange as $date) {
$months[] = $date->format("F");
echo '<th>Daily</th>';
echo '<th>Cumulative</th>';
}
echo '</tr>';
// Table Body
$sumc = array();
for ($d = 1; $d <= 31; $d++) {
echo '<tr><td>'.$d.'</td>';
foreach ($months as $month) {
$db_date = $month.'-'.$d; // used for db query
// dummmy data (replace with db query result)
$sum = mt_rand(0, 999);
echo '<td>'.$sum.'</td>';
if(!array_key_exists($month, $sumc)) {
$sumc[$month] = 0;
}
$sumc[$month] = (int)$sum + $sumc[$month];
echo '<td>'.$sumc[$month].'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
Also the condition:
Where there is a weekend or the date is invalid i want the value to be
zero.
is it correct to assume that these are taken care because the DB query would return 0? Or do you have to check in the code for weekends even if the DB query returns an amount from total_disb that is >0?
You have just messed up a little with dates, if I'm understanding where your problem is you can do it directly from SQL, try something like:
SELECT SUM(amount) AS total_disb , MONTH(DateTime) , DAY(DateTime)
FROM payments
GROUP BY DATE(DateTime), DAY(DateTime)
Change DateTime for your variable or column names.
If you also want to SUM the months totals at the end of the table I'd recommend you to make a new query like:
SELECT SUM(amount) AS total_disb , MONTH(DateTime)
FROM payments
GROUP BY DATE(DateTime), MONTH(DateTime)
Another option would be to increment a variable while you loop to print the values, but in my opinion a new query is more simple.
If this is not what you need leave a comment and I will edit it.
To get to the cumulative you have to store the previous sum result and add it to the current iteration in the loop, something like:
$sumc = array();
foreach($mnth as $mon) {
$dat = $mon . $d;
$qry = mysql_query("SELECT SUM(amount) AS total_disb FROM payments where dat='$dat'") or die(mysql_error());
$row = mysql_fetch_assoc($qry);
$sum = $row['total_disb'];
if(isset($sumc[$mon])) {
$sumc[$mon] = (int)$sum + $sumc[$mon];
} else {
$sumc[$mon] = (int)$sum;
}
echo "<td>" . $sum . "</td>";
echo "<td>" . $sumc[$mon] . "</td>";
}
should probably work.
(Note: that you are missing a second row for 'daily' and 'cumulative' and once you have that row you need to use colspan to span the columns of the Months across). See an example of colspan here.

Getting appointments for the next 5 days using php

I am trying to write a script to pull dates for the next 7 days and put them into a div for each date :
echo '<div class="dateboxcontainer">';
for($i=0; $i<=6; $i++){
echo '<div class="datebox"><div class="topdate">'.strtoupper(date("D d", mktime(0, 0, 0, 0, date("d")+$i, 0))."\n").
'</div><div class="bottomdate">An appointment for the day</div></div>';
}
echo '</div>';
Im now trying to pull data from my database from two fields 'datedroppingoff' and 'datepickingup', which are formatted like this '2013-07-10 14:29:28'.
Im kind of stuck though as im not sure what query to write to put the appointments for each day into each day div where 'some info' currently sits.
Im guessing it would be something like
Select * FROM jobdetails WHERE datedroppingoff OR datepickingup = WHATEVER DAY IS BEING ECHO'D OUT
but im not quite sure how I can compare the date stored in jobdetails for that row to the date being echo'd out ?.
Edit>>>>>
Thanks for the answers below, iv managed to come up with the following, it echos out the date boxes ok, but doesnt bring in any data, so im not sure if I have the sql part correct ?.
echo '<div class="dateboxcontainer">';
$eventdata = <<<SQL
SELECT *
FROM `jobdetails`
SQL;
if(!$events = $db->query($eventdata)){
die('There was an error running the query [' . $db->error . ']');
}
// read first event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the first one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $datedroppingoff;
} else // no events?
$nextDate = 0; // prepare a fake date value
// calculate today date
$currentDate = mktime();
// loop on the dates for the next 7 days
for ($i = 0 ; $i < 7; $i++) {
$currentEvents = "";
// loop to print every event for current day (first one already extracted)
while ($nextDate == date("Y-m-d", $currentDate)) { // next event occurs today
// here prepare the var containing the event description
// BTW, I'd use a list for the events
$currentEvents .= "· $name<br>"; // use every field you need from current DB row
// read next event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the next one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $datedroppingoff;
} else // no more events?
$nextDate = 0; // prepare a fake date value
}
echo "
<div class='datebox'>
<div class='topdate'>" . strtoupper(date("D d m Y", $currentDate)) . "</div>
<div class='bottomdate'>$currentEvents</div>
</div>";
$currentDate = strtotime("+1 day", $currentDate);
}
echo '</div>';
Can you use something like this:
SELECT * FROM `jobdetails` WHERE (`datedroppingoff ` > '2013-07-01 00:00:00' AND `datedroppingoff ` '2013-07-02 00:00:00') OR (`datepickingup ` > '2013-07-01 00:00:00' AND `datepickingup ` '2013-07-02 00:00:00');
This will have to be repeated per day (i.e. for each of the 5 days)
To do a nice loop, use an array populated with the next 5 dates as strings. Then do a foreach over the dates and run this query.
If you want all dates from now and for the next 5 days, you could use:
WHERE
`datedroppingoff` BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 5 DAY) OR
`datepickingup ` BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 5 DAY)
Let's see how I'd proceed (by the way, this is my first answer, so I'm a little excited...)
First, some basic assumptions for this ultra-fast script (sorry, not so much time now to test it thoroughly).
your Appointment table has a field with the date of the appointment
your result resource ($events) contains only the rows for the current week
the resulting rows are sorted by the date field, ascending (from oldest to newest)
Try this (I've changed a bit your original code, sorry)
// read first event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the first one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $DB_field_with_event_date;
} else // no events?
$nextDate = 0; // prepare a fake date value
// calculate today date
$currentDate = mktime();
// loop on the dates for the next 7 days
for ($i = 0 ; $i < 7; $i++) {
$currentEvents = "";
// loop to print every event for current day (first one already extracted)
while ($nextDate == date("Y-m-d", $currentDate)) { // next event occurs today
// here prepare the var containing the event description
// BTW, I'd use a list for the events
$currentEvents .= "· $your_desc_field<br>"; // use every field you need from current DB row
// read next event
if ($nextEvent = mysql_fetch_assoc($events)) { // here is the next one
extract($nextEvent); // prepare its variables
// use the event date it to control the inner loop
$nextDate = $DB_field_with_event_date;
} else // no more events?
$nextDate = 0; // prepare a fake date value
}
echo "
<div class='datebox'>
<div class='topdate'>" . strtoupper(date("D d m Y", $currentDate)) . "</div>
<div class='bottomdate'>$currentEvents</div>
</div>";
$currentDate = strtotime("+1 day", $currentDate);
}
Tried a couple of times on fake data and it should work. IMHO better to directly alias the date field to get the nextDate var directly from the DB, so avoiding the rows,
$nextDate = $DB_field_with_event_date;
I used this in the end which seems to do the job ! :)
// Date box container
echo '<div class="dateboxcontainer">';
// Loop through and create a date for the next 7 days
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 7);
foreach ($days as $day) {
echo '<div class="datebox">';
echo '<div class="topdate">';
echo strtoupper($day->format('D d')) . PHP_EOL;
echo '</div>';
// Get the names for each day
$theday = strtoupper($day->format('Y-m-d'));
$sqldate = <<<SQL
SELECT *
FROM `jobdetails`
WHERE datedroppingoff = '$theday' OR datepickingup = '$theday'
SQL;
if(!$resultdate = $db->query($sqldate)){
die('There was an error running the query [' . $db->error . ']');
}
while($rowdate = $resultdate->fetch_assoc()){
echo $rowdate['name'];
}
//
echo '</div>';
}
echo '</div>';
//

PHP Calendar displaying list of events

I have a database table that has two columns eventName|eventDate. I have created a function that takes in a startDate and endDate, I want to display the list of events in a ListView with each date as the header.
In my brief example below, I know I can retrieve the full event listings with SQL. How do I then slot the event headers in so that I can return them in a properly formatted array?
function retrieveEvents($startDate, $endDate) {
// run SQL query
//
if($stmt->rowCount() > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// how do I write this part such that I can output event headers in my array
$events = $row;
}
}
}
So my intended output is
1st July 2013 ($startDate)
- Tea with President - 1300h
- Mow the lawn - 1330h
- Shave the cat - 1440h
2nd July 2013
- Shave my head - 0800h
3rd July 2013
4th July 2013 ($endDate)
- Polish the car - 1000h
In your MYSQL query:
SELECT * FROM `yourTableName` WHERE `eventDate` >= $startDate AND `eventDate` <= $endDate
PS: I'm not sure about the quotes arount the variables in your query.
PPS: never use * to select your columns, always only select the columns you need. Here I'm using it because I don't know the names of your columns
I ended up doing my checking in PHP and print a new row only when a different date is detected.
Codes below in case it serves someone's needs in future.
<?php
$currentPrintDay = 0;
$currentPrintMonth = 0;
$currentPrintYear = 0;
echo "<table>"
foreach($reservationsToShow as $row):
// get day, month, year of this entry
$timestamp = strtotime($row['timestamp']);
$day = date('d', $timestamp);
$month = date('m', $timestamp);
$year = date('Y', $timestamp);
// if it does not match the current printing date, assign it to the current printing date,
// assign it, print a new row as the header before continuing
if($day != $currentPrintDay || $month != $currentPrintMonth || $year != $currentPrintYear) {
$currentPrintDay = $day;
$currentPrintMonth = $month;
$currentPrintYear = $year;
echo
"<tr>" .
"<td colspan='100%'>". date('d-m-Y', $timestamp) . "</td>" .
"</tr>";
}
// continue to print event details from here on...
?>

Categories