Table starting from present date - php

$sqlStr = "SELECT name, datescheduled
FROM table
WHERE datescheduled > NOW()
ORDER BY datescheduled DESC";
I would like to echo a table with the results above. I would like a row for each day for the next 90 days regardless of whether or not the MySQL table has an entry for that day. How can I do this?

Add:
$query1 = mysql_query($sqlStr);
echo "<table><tr>";
echo "<th>Name</th><th>Date Scheduled</th>";
while ($rows = mysql_fetch_assoc($query1)) {
echo "<td>" .$rows['name']. "</td>";
echo "<td>" .$rows['datescheduled']. "</td>";
}
echo "</tr><table>";

//select rows for next 90 days and read them into $rows
//use datescheduled as the key
//assumes there will only be 1 row per date and datescheduled is in Y-m-d format
$sqlStr = "SELECT name, datescheduled
FROM table
WHERE datescheduled > NOW()
AND datescheduled < date_add(now(),INTERVAL 90 DAY)
ORDER BY datescheduled DESC";
$rs = mysql_query($sqlStr);
$rows = array();
while($r = mysql_fetch_assoc($rs)) {
$rows[$r['datescheduled']] = $r;
}
//add missing dates to $rows with name = false
$begin = new DateTime();
$end = new DateTime();
$end->modify('+90 day');
$interval = new DateInterval('P1D');
$period = new DatePeriod($begin, $interval, $end);
//iterate through the next 90 days
foreach ($period as $dt) {
$date_key = $dt->format( "Y-m-d" );
if(!isset($rows[$date_key])) {
//table doesn't contain a row for this date, so add it
$rows[$date_key] = array('datescheduled' => $date_key, 'name' => false);
}
}
//do something with $rows

So you can use this basic setup. I assume based on your wording that there would only be one entry per row, but it would be easy to adjust accordingly.
//Get the current date
$date = date('Y-m-d');
//Set the table header
$str = '<table><thead><tr><th>Name</th><th>Date</th></tr></thead><tbody>';
//START THE WHILE LOOP GETTING THE FETCH ASSOC
//Go through for 90 days
for ( $i = 0; $i < 90; $i++ ) {
$str .= '<tr>';
if ( $row['date'] == date('Y-m-d', strtotime('-'.$i.' day', $date)) {
$str .= '<td>'.$row['name'].'</td><td>'.$row['date'].'</td>';
} else {
$str .= '<td></td><td></td>';
}
$str .= '</tr>';
}
//END WHILE LOOP NOT INCLUDED
$str .= '</table>';
echo $str;

Related

Get all months from a query including zero counts

I have this query now:
SELECT DATE_FORMAT(`dataNl`, \'%Y%m\') AS `Ym`, COUNT(*) AS `totale`
FROM `noleggio`
GROUP BY `Ym`
This help to get data for each month, but if a month with 0 value, this doesn't exist in the database, so I can't get it. I need a query that add remaining month setting the COUNT field to 0.
I made a PHP code to add months with 0 value into the array, but it only works if the year is only one, if I want to get more, this needs a lot of tricky code, I think there could be a solution with SQL.
This is the PHP code:
$t = array();
$m = array();
foreach ($months as $val) {
$t[] = $val['totale'];
$m[] = $val['Ym'];
}
for ($i = 0; $i < 12; ++$i) {
if (in_array($i + 201801, $m) == false) {
array_splice($t, $i, 0, 0);
}
}
Here is a PHP solution which requires min and max dates from the database:
// use the query SELECT MIN(dataNl), MAX(dataNl) FROM ... to
// find the first and last date in your data and use them below
$dates = new DatePeriod(
DateTime::createFromFormat('Y-m-d|', '2018-01-15')->modify('first day of this month'),
new DateInterval('P1M'),
DateTime::createFromFormat('Y-m-d|', '2018-12-15')->modify('first day of next month')
);
// assuming $rows contain the result of the GROUP BY query...
foreach ($dates as $date) {
$datestr = $date->format('Ym');
$index = array_search($datestr, array_column($rows, 'Ym'));
if ($index === false) {
echo $datestr . ' -> 0' . PHP_EOL;
} else {
echo $datestr . ' -> ' . $months[$index]['totale'] . PHP_EOL;
}
}
Try the below query:
SELECT DATE_FORMAT(`dataNl`, \'%Y%m\') AS `Ym`, COUNT(*) AS `totale`
FROM `noleggio`
GROUP BY MONTH(`dataNl`)

Inputting/overwriting information in arrays with PHP

I have a small PHP page which takes data from MySQL and displays it via PHP in a monthly calendar. I'm having trouble arranging the data properly within an array to get the desired output.
First, I will describe what I would like to happen:
students come to classes on regular days of the week
they can also make or cancel reservations
the calendar also displays days when the school is not open
In order to display this data on the calendar, I use MySQL to output data from a variety of sources, and then input that into an array with PHP, which I sort by date and output.
My issue is, I would like to be able to handle more than one row of data per day, but because I am using the date as the key, I am limited on only displaying one result per day. If I use a loop to append the date with a counter in the key, I get overlapping results in situations where someone made a reservation and then cancelled that reservation on the same day.
As for my code...
First, I check to see if the student is registered in a weekly class, then input that class into the array.
$sql = "SELECT StudentDB.studentid, ClassDB.classID, ClassDB.class_level, ClassDB.class_title, ClassDB.time, ClassDB.teacher, StudentDB.first_name, StudentDB.last_name, StudentDB.payment_amount, ClassDB.day
FROM ClassDB
INNER JOIN RegDB ON ClassDB.classID = RegDB.classid
INNER JOIN StudentDB ON StudentDB.studentID = RegDB.studentid
WHERE StudentDB.studentid = '$studentid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { // DISPLAY REGULAR CLASS DATA
$dayofclass = $row['day'];
$class_level = $row['class_level'];
$class_title = $row["class_title"];
$day = $row["day"];
$class_time = $row["class_time"];
$time = $row["time"];
// check which dates match the days of the week and store in an array
for ($i=1;$i<=$n;$i++){
if ($i<10) {
$i = "0" . $i;
}
$day=date("l",strtotime($yearmonth.$i)); //find weekdays
if($day==$dayofclass){
$time = date("H:i",strtotime($row['time']));
$dates[]=$yearmonth.$i;
$datesdata[$yearmonth.$i] = "0";
$timedata[$yearmonth.$i] = $time;
$classiddate[$yearmonth.$i] = $row['classID'];
}
}
}
echo "</table>";
$conn->close();
}
After that, I check for specific reservations (cancelations, irregular reservations, waitlists) and input them into the array:
$lowerlimit = $yearmonth . "01";
$upperlimit = $yearmonth . "31";
$sql = "SELECT AttendanceDB.*, ClassDB.*
FROM StudentDB
INNER JOIN AttendanceDB ON StudentDB.studentid = AttendanceDB.studentid
INNER JOIN ClassDB ON AttendanceDB.classid = ClassDB.classID
WHERE StudentDB.studentid = '$studentid'
AND AttendanceDB.class_time >= '$lowerlimit'
AND AttendanceDB.class_time <= '$upperlimit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$loopcount = 0;
// store furikae data in the array
while($row = $result->fetch_assoc()) {
$phpdate = strtotime( $row["class_time"] );
$time = date("H:i",strtotime($row['time']));
$mysqldate = date( 'Y-m-d', $phpdate );
$loopcount++;
$mysqldate = $mysqldate . "+" . $loopcount;
// $loopcount++;
// $mysqldate = $mysqldate . "+" . $loopcount;
$previousdate = $mysqldate;
$previousfurikae = $row['furikae'];
if ($row["furikae"] == 3){
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "1";
$timedata[$mysqldate] = $time;
$classiddate[$mysqldate] = $row['classID'];
} elseif ($row["furikae"] == 8 OR $row["furikae"] == 7) {
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "3";
$timedata[$mysqldate] = $time;
} elseif ($row["furikae"] == 2) {
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "2";
$timedata[$mysqldate] = $time;
}
}
}
$conn->close();
Then finally I check the school calendar and input the days off into the array:
$sql = "SELECT *
FROM SchoolScheduleDB
WHERE date >= '$lowerlimit'
AND date <= '$upperlimit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// store furikae data in the array
while($row = $result->fetch_assoc()) {
$phpdate = strtotime( $row["date"] );
// $time = date("H:i",strtotime($row['time']));
// $mysqldate = date( 'Y-m-d', $phpdate ) . " " . $time;
$mysqldate = date( 'Y-m-d', $phpdate );
$dates[]=$mysqldate;
$datesdata[$mysqldate] = "666";
}
}
$conn->close();
The way I intended it to work was that:
First the regular classes would be input
Then any reservations would overwrite the original plans
And finally the school calendar would overwrite everything
Currently, this functions as it should, but it is limited to displaying 1 result per day, but I would like to be able to display more than 1 result per day for students who come to multiple classes.
Thank you for your help. If I made any mistakes in my question or my question is unclear I will do my best to revise it.
You can make a Sub-Array for each date by using edged brackets:
$data[20180528][] = 'aa';
$data[20180528][] = 'bb';
$data[20180529][] = 'cc';
$data[20180529][] = 'dd';
$data[20180529][] = 'ee';
will give you an Array like this:
20180528 => aa
=> bb
20180529 => cc
=> dd
=> ee

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.

Print out custom name of the month in php

I can't figure it out! I've created an array of months in "Slovenian language" and now, I would want to display my month's name instead of the number. Instead of working, it writes out - 32014vEurope/Berlin11bEurope/BerlinWed and some more weird stuff, it should obviously print out November in my case. I would like to solve this problem with arrays, but It just wouldn0t convert the number of 'n' to the requested month.
function kliknjena($link, $mojster)
{
$meseci[1] = "Januar";
$meseci[2] = "Februar";
$meseci[3] = "Marec";
$meseci[4] = "April";
$meseci[5] = "Maj";
$meseci[6] = "Junij";
$meseci[7] = "Julij";
$meseci[8] = "Avgust";
$meseci[9] = "September";
$meseci[10] = "Oktober";
$meseci[11] = "November";
$meseci[12] = "December";
$sql = "SELECT naslov, podnaslov, vsebina, ustvarjeno, slug FROM novica
where slug = '$mojster'
limit 1";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<h1>".$row["naslov"]."</h1>";
$timestamp = strtotime($row["ustvarjeno"]);
$m = date("n", $timestamp);
echo date("d. $meseci[$m]; Y, H:i:s", $timestamp);
echo "<p>".$row["podnaslov"]."</p>"."<br>";
echo "<p>".$row["vsebina"]."</p>"."<br>";
}
}
else
{
echo "0 results";
}
}
Use:
echo date('d. ', $timestamp) . $meseci[$m] . date('; Y, H:i:s', $timestamp);
What's happening is that the month name is being substituted into the date() argument, and then all the letters in the month are being treated as formatting characters, so they get replaced with the corresponding fields from the date and time.

sql search whilst in a foreach loop or while loop

Hi firstly heres my code.
<?php
function getDatesBetween2Dates($startTime, $endTime) {
$day = 86400;
$format = 'd-m-Y';
$startTime = strtotime($startTime);
$endTime = strtotime($endTime);
$numDays = round(($endTime - $startTime) / $day) + 1;
$days = array();
for ($i = 0; $i < $numDays; $i++) {
$days[] = date($format, ($startTime + ($i * $day)));
}
return $days;
}
///
$days = getDatesBetween2Dates(date('d-m-Y', strtotime('-3 weeks Monday')),date('d-m-Y', strtotime('+2 weeks Sunday')));
foreach($days as $key => $value){
$dayNumber = date('d', strtotime($value));
//echo $value;
echo "<div id=\"day\">
<div id=\"number\">$dayNumber</div>";
////////////sql seearch//\\\/////////
//Connect to db
include("../djwbt.php");
$sql = "SELECT * FROM daysummary WHERE date='$value'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$place = $row['place'];
$invoicedate = $row['date'];
}
/////////////end sql search//////////
echo "<div id=\"event\">$place</div>
</div><!-- end day -->";
}
?>
What i am trying to do is show all dates between two points and for each of the dates search my db using the date as a where clause. i have tried putting the search in a few places but im not getting the right results.
this gives me the same result in each date.
e.g. 17th = (empty) as in my db, 18TH = HOME (as in my db), 19th = HOME (not as in my db), 20th = HOME (this continues all the way through fore each)
the link in each fore each works perfectly?
Any help would be amazing.
I would make one statement that gets all the needed data from your database:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
then use the foreach loop for the results
Note that mysql_ functions are deprecated, Try switching to mysqli_ or PDO

Categories