Not sure how to name correctly this question so feel free to edit if is needed.
I have 12 boxes one per month, and each box display:
1 - A message like "Sold" or "Available" depending on the info coming from the database.
2 - The name of the month and the year, if the month is older than the current month the year will be increased by one.
The info coming from the database have a few values separated by a | symbol, the pertinent one to check is the las one, an example value of $row['custom'] is: 93 | Supper | New Port | August - 2012
My problem is that I need to update each box with their "status" and with the current script only the las entry on the database is used to update the boxes, so In cases where i know there is two or more boxes that should display the message "Sold", only the most recent is the updated.
How can I modify the following script to update one by one box ?
The problem is the way I'm querying the database or something else ?
Thanks in advance for any help or advice.
Code only for 2 of 12 month, to make things short
<?php
$month = date("m"); // Current month
$year = date("Y"); // Current year
$next = strtotime(date("d-m-Y", strtotime($now)) . "+1 year");
$nextyear = date("Y", $next); // Next year
// Check if this month is gone or not, if gone replace current year with next year
$january = "01";
$february = "02";
if ($month > $january) {
$jan = 'January - ' . $nextyear; } else { $jan = 'January - ' . $year;}
if ($month > $february) {
$feb = 'February - ' . $nextyear; } else { $feb = 'January - ' . $year;}
//Get info from Database
$query = "SELECT `custom` FROM `payments` WHERE `status` = 'Pending' OR `status` = 'Completed'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$check_custom = explode(" | ", $row['custom']);
$month_sold = $check_custom[3];
}
// Check if month is sold or not
if ($month_sold == $jan) { $jan_status = 'Sold';} else { $jan_status = 'Available';}
if ($month_sold == $feb) { $feb_status = 'Sold';} else { $feb_status = 'Available';}
//Output the months and their status
?>
<div class="month">
<div class="mname"><?php echo $jan;?></div>
<div class="<?php echo $jan_status;?>">
<?php echo $jan_status;?>
</div>
<?php if($jan_status == 'Available') {
echo 'This month is ' . $jan_status . '.';
} else {
echo 'This month has been ' . $jan_status . '.';} ?>
</div>
<div class="month">
<div class="mname"><?php echo $feb;?></div>
<div class="<?php echo $feb_status;?>">
<?php echo $feb_status;?>
</div>
<?php if($feb_status == 'Available') {
echo 'This month is ' . $feb_status . '.';
} else {
echo 'This month has been ' . $feb_status . '.';} ?>
</div>
You misplaced the closing bracket of while and move the `$jan_status='Available' from inside while loop to just above it; Here is the modified code
<?php
$month = date("m"); // Current month
$year = date("Y"); // Current year
$next = strtotime(date("d-m-Y", strtotime($now)) . "+1 year");
$nextyear = date("Y", $next); // Next year
// Check if this month is gone or not, if gone replace current year with next year
$january = "01";
$february = "02";
if ($month > $january) {
$jan = 'January - ' . $nextyear; } else { $jan = 'January - ' . $year;}
if ($month > $february) {
$feb = 'February - ' . $nextyear; } else { $feb = 'January - ' . $year;}
//Get info from Database
$query = "SELECT `custom` FROM `payments` WHERE `status` = 'Pending' OR `status` = 'Completed'";
$result = mysql_query($query) or die(mysql_error());
$jan_status = 'Available';
$feb_status = 'Available';
while($row = mysql_fetch_array($result)) {
$check_custom = explode(" | ", $row['custom']);
$month_sold = $check_custom[3];
// Check if month is sold or not
if ($month_sold == $jan) { $jan_status = 'Sold';}
if ($month_sold == $feb) { $feb_status = 'Sold';}
}//th closing bracket should be here;
//Output the months and their status
?>
<div class="month">
<div class="mname"><?php echo $jan;?></div>
<div class="<?php echo $jan_status;?>">
<?php echo $jan_status;?>
</div>
<?php if($jan_status == 'Available') {
echo 'This month is ' . $jan_status . '.';
} else {
echo 'This month has been ' . $jan_status . '.';} ?>
</div>
<div class="month">
<div class="mname"><?php echo $feb;?></div>
<div class="<?php echo $feb_status;?>">
<?php echo $feb_status;?>
</div>
<?php if($feb_status == 'Available') {
echo 'This month is ' . $feb_status . '.';
} else {
echo 'This month has been ' . $feb_status . '.';} ?>
</div>
Every time you run $row = mysql_fetch_array(), it replaces the contents of $row with the next row from the database. Look at the while loop: it assigns values to $check_custom and $month_sold, but doesn't do anything with them before overwriting them with new values. You need to move all your code for parsing the database output and generating the info for a given month inside the loop. Then output or save the information you want to display for that month before it goes on to the next one.
There's a lot you could do to make your code simpler and easier to maintain. For example, I would make an array for the months and iterate over that, rather than creating a separate set of variables and separate output code for each month. Also, what you're doing with your custom column right now is using a field in your database table to store another tiny table. This creates a lot of problems -- if you broke that data out into multiple columns, you could just do a query for the appropriate month and year.
Move your status checks into the loop so that it operates on every row from the database. Otherwise you only wind up referring to the row returned by the last call of mysql_fetch_array. I would recommend using a switch statement for readability, though.
while($row = mysql_fetch_array($result)) {
$check_custom = explode(" | ", $row['custom']);
$month_sold = $check_custom[3];
// Check if month is sold or not
if ($month_sold == $jan) { $jan_status = 'Sold';}
else { $jan_status = 'Available';}
if ($month_sold == $feb) { $feb_status = 'Sold';}
else { $feb_status = 'Available';}
}
Related
I'm creating a calendar with Sunday being the start of each week and I want to present the week number of the year before each row of dates.
This is my calendar
my calendar
How can I add week numbers like this:
This is what I need
My code:
<?php
function generate_calendar($month, $year) {
$calendar = array();
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$first_day_of_month = date('w', strtotime("$year-$month-01"));
$week_number = 1;
$week = array();
// Determine the week number offset
$days_from_january_1st = strtotime("$year-01-01");
$days_to_first_day_of_month = strtotime("$year-$month-01");
$week_number_offset = floor(($days_to_first_day_of_month - $days_from_january_1st) / 604800);
// Check if the last week of the previous month is full (7 days)
$last_week_of_previous_month = $week_number_offset;
if ($month > 1) {
$previous_month = $month - 1;
$previous_month_year = $year;
$previous_month_year = date("Y", strtotime("-1 month" , strtotime("$year-$month-01")));
$previous_month = date("n", strtotime("-1 month" , strtotime("$year-$month-01")));
if ($previous_month == 0) {
$previous_month = 12;
$previous_month_year = $year - 1;
}
$days_in_previous_month = cal_days_in_month(CAL_GREGORIAN, $previous_month, $previous_month_year);
$last_day_of_previous_month = date('w', strtotime("$previous_month_year-$previous_month-$days_in_previous_month"));
if ($last_day_of_previous_month == 6) {
$last_week_of_previous_month=$last_week_of_previous_month + 1;
} else {
// Check if the last week of the previous month only has a few days
$last_week_of_previous_month = $last_week_of_previous_month;
}
}
// Generate the previous month's days
for ($i = 1; $i <= $first_day_of_month; $i++) {
array_unshift($week, "");
}
// Generate the current month's days
for ($i = 1; $i <= $days_in_month; $i++) {
$week[] = $i;
if (count($week) == 7) {
$calendar[$week_number + $last_week_of_previous_month] = $week;
$week_number++;
$week = array();
}
}
// Generate the next month's days
$remaining_days = 7 - count($week);
for ($i = 1; $i <= $remaining_days; $i++) {
$week[] = '';
}
if (!empty($week)) {
$calendar[$week_number + $last_week_of_previous_month] = $week;
}
return $calendar;
}
$year = 2022;
echo "<table>\n";
echo " <tr>\n";
echo " <th colspan='3'>$year</th>\n";
echo " </tr>\n";
echo " <tr>\n";
for($i=1; $i<=12; $i++){
$month_name = date('F Y', strtotime("$year-$i-01"));
$calendar = generate_calendar($i, $year);
echo "<td>\n";
echo "<table>\n";
echo " <tr>\n";
echo " <th colspan='8'>$month_name</th>\n";
echo " </tr>\n";
echo " <tr>\n";
echo " <th>Week</th>\n";
echo " <th>Sun</th>\n";
echo " <th>Mon</th>\n";
echo " <th>Tue</th>\n";
echo " <th>Wed</th>\n";
echo " <th>Thu</th>\n";
echo " <th>Fri</th>\n";
echo " <th>Sat</th>\n";
echo " </tr>\n";
foreach ($calendar as $week_number => $week) {
echo " <tr>\n";
echo " <td>$week_number</td>\n";
foreach ($week as $day) {
if (empty($day)) {
echo " <td></td>\n";
} else {
echo " <td>$day</td>\n";
}
}
echo " </tr>\n";
}
echo "</table>\n";
echo "</td>\n";
if($i==3 || $i==6 || $i==9){
echo " </tr>\n";
echo " <tr>\n";
}
}
echo " </tr>\n";
echo "</table>\n";
?>
Trying to add week number which counts from first week of January (if last week of previous month is not full 7 days then first week of current month start from last week of previous month), but my code only count from first week of current month.
I managed to get the right result (as far as I tested) with IntlCalendar and its FIELD_WEEK_OF_YEAR constant instead of counting Sundays.
I did some refactoring of your function, but ran out of time to do a full reduction of the script (there may still be lines that can be simplified/condensed).
Code: (Demo)
function generate_calendar(int $month, int $year) {
$calendar = [];
$week_number = (IntlCalendar::fromDateTime ("$year-$month-01"))->get(IntlCalendar::FIELD_WEEK_OF_YEAR);
$month_start = new DateTime("$year-$month-01");
// Generate the previous month's days
if ($first_day = $month_start->format('w')) {
$week = array_fill(1, $first_day, '');
}
// Generate the current month's days
$days_in_month = $month_start->format('t');
for ($i = 1; $i <= $days_in_month; $i++) {
$week[] = $i;
if (count($week) == 7) {
$calendar[$week_number] = $week;
$week_number++;
$week = [];
}
}
if ($week) {
// Generate empty days for the next month
$calendar[$week_number] = array_pad($week, 7, '');
}
return $calendar;
}
I don't believe there is any way to set the start day of the week in the standard library of PHP without manual calculation, but you can do it easily with the intl library (make sure the intl PHP extension is enabled):
$cal = IntlGregorianCalendar::createInstance();
// Set start of week to Sunday
$cal->setFirstDayOfWeek(IntlGregorianCalendar::DOW_SUNDAY);
// Get week number of the year for the current date
$weekOfYear = intval(IntlDateFormatter::formatObject($cal, 'w'));
// Advance to the next week
$cal->add(IntlGregorianCalendar::FIELD_WEEK_OF_YEAR, 1);
// ect...
I have a calendar script that displays up to 6 appointments per morning and per afternoon on any given day. It counts how many are remaining and if all 6 are taken then displays FULL. What I would also like to do is to be able to block out a morning, afternoon, whole day or even whole week (for a holiday for example) and mark them as FULL without having to add 6/12/84 individual rows to the db.
I have tried adding a column called 'block' and setting it's value to 1 for a given day, 0 as default, but I can't get both queries to run at the same time. It then doesn't display the days that still have 6 appointments (i.e. don't have any rows in the db therefore don't have a block value of 0 OR 1). I've tried every which way of nesting 2 while loops and I've tried IF EXISTS in the sql, exists/isset in the PHP but just can't get it to work. Can anyone please help?
date_default_timezone_set('Europe/London');
// Get prev & next month
if (isset($_GET['ym'])) {
$ym = $_GET['ym'];
} else {
// This month
$ym = date('Y-m');
}
// Check format
$timestamp = strtotime($ym . '-01'); // the first day of the month
if ($timestamp === false) {
$ym = date('Y-m');
$timestamp = strtotime($ym . '-01');
}
// Today (Format:2018-08-8)
$today = date('Y-m-d');
$todaynum = date('N');
$hour = date('a');
// Title (Format:August, 2018)
$title = date('F, Y', $timestamp);
// Display Month (Format: August), Display Year (Format: 2018)
$dismth = date(' F ', $timestamp);
$disyr = date('Y', $timestamp);
// Current Year (Format:2018-), Current Month (Format:08-),
$curryr = date('Y-', $timestamp);
$currmth = date('m-', $timestamp);
// Create prev & next month link
$prev = date('Y-m', strtotime('-1 month', $timestamp));
$next = date('Y-m', strtotime('+1 month', $timestamp));
// Number of days in the month
$day_count = date('t', $timestamp);
// 1:Mon 2:Tue 3: Wed ... 7:Sun
$str = date('N', $timestamp);
// Array for calendar
$weeks = [];
$week = '';
// Add empty cell(s)
$week .= str_repeat('<td></td>', $str - 1);
for ($day = 1; $day <= $day_count; $day++, $str++) {
/* create a variable to concantenate the dates into db format */
/*$chosen = $curryr.$currmth.$day;*/
if ($day < 10) {
$date = $ym . '-0' . $day;
}
else {
$date = $ym . '-' . $day;
}
/* find if it's a weekend */
$weekdays = strtotime($date);
$weekday = date('l', $weekdays);
/* create a variable to concantenate the day and dates into display format */
$display = $weekday.', '.$day.$dismth.$disyr;
/* query - count number of appointments for current day and time */
$sqlam = "SELECT count(*) AS amapp FROM wasps_appointments WHERE date = '$date' AND time = 'Morning'";
$resultam = $connection->query($sqlam);
$sqlpm = "SELECT count(*) AS pmapp FROM wasps_appointments WHERE date = '$date' AND time = 'Afternoon'";
$resultpm = $connection->query($sqlpm);
/* start cell - check if today and if yes add class */
if ($today == $date) {
$week .= '<td class="today">';
} else {
$week .= '<td>';
}
/* Write day number into cell */
$week .= '<span class="date">';
$week .= $day;
$week .= '</span>';
/* if weekend show nothing */
if ( $weekday == 'Saturday' || $weekday == 'Sunday' ){ }
/* else (if not weekend) show links */
else {
/* ------------------------ MORNING -----------------------*/
/* display morning appointment availability from query above */
while($row = mysqli_fetch_array($resultam)){
/* if in the future show links */
if ($date >= $today){
/* count how many remaining */
$amremain = 6 - $row['amapp'];
/* change colour according to availability*/
$trafficlight = "green";
if ($amremain == 3 || $amremain == 2) { $trafficlight = "amber";}
elseif ($amremain == 1) { $trafficlight = "red";}
/* check if fully booked */
if ($amremain == 0) {
$week .= 'am <span class="am full">FULL</span><br />';
}
else {
/* write dates into form fields from link */
$week .= 'am <span class="am '.$trafficlight.'">' . $amremain . ' left</span><br />';
}
}
/* else if in the past show nothing */
else { }
}
/* ------------------------ END MORNING -----------------------*/
/* ------------------------ AFTERNOON -----------------------*/
/* display afternoon appointment availability from query above */
while($row = mysqli_fetch_array($resultpm)){
/* if in the future show links */
if ($date >= $today){
$pmremain = 6 - $row['pmapp'];
/* change colour according to availability*/
$trafficlight = "green";
if ($pmremain == 3 || $pmremain == 2) { $trafficlight = "amber";}
elseif ($pmremain == 1) { $trafficlight = "red";}
if ($pmremain == 0) {
$week .= 'pm <span class="pm full">FULL</span>';
}
else {
/* write dates into form fields from link */
$week .= 'pm <span class="pm '.$trafficlight.'">' . $pmremain . ' left</span>';
}
}
/* else if in the past show nothing */
else { }
}
/* ------------------------ END AFTERNOON -----------------------*/
}
/* end cell */
$week .= '</td>';
// Sunday OR last day of the month
if ($str % 7 == 0 || $day == $day_count) {
// last day of the month
if ($day == $day_count && $str % 7 != 0) {
// Add empty cell(s)
$week .= str_repeat('<td></td>', 7 - $str % 7);
}
$weeks[] = '<tr>' . $week . '</tr>';
$week = '';
}
}
?>
<div id="calendar">
<div class="datenavigation">< prev <span class="title"><?= $title; ?></span> next ><!-- today--></div>
<div class="key"><span class="am">Morning 8am to 12pm</span><br /><span class="pm">Afternoon 1pm to 6pm</span></div>
<table>
<thead>
<tr>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
<th>S</th>
</tr>
</thead>
<tbody>
<?php
foreach ($weeks as $week) {
echo $week;
}
?>
</tbody>
</table>
</div>
I have following code where inside image tag I open php tag and decide different images based on ifelse() condition. I want to add different titles for the images selected but could not come up with a solution. The code is as follows:
<img title = "Last assessment for this child was submitted <?php if ($time == 0){echo $time;}else{echo $time - 1;}?> Month(s) ago."
src="<?php
if ($record->$period == 0) { echo base_url()."img/warning.png";}
else{
date("M d, Y", strtotime($record->$period));
$vtime = new DateTime($record->$period); ///////////////////////
$today = new DateTime(); // for testing purposes ///Calculate Time period//
$diff = $today->diff($vtime); ///
$time = $diff -> m;
if($time <= 4)
{echo base_url()."img/green.png";}
elseif( $time > 4 && $time <= 6)
{echo base_url()."img/yellow.png";}
elseif($time >= 6)
{echo base_url()."img/red.png";}
}
"
/>
I want different title for the first condition. i.e. If the first condition is true and the image shown is "warning.png". Then the image title should be "Check record" instead of title "last assessment submitted was ...."
Any help is much appreciated.
You can simply use the following. Just nest current if...else condition in another if...else condition on title tag also.
<img title = "
<?php if($record->period==0)
echo "Check record";
else { ?>
Last assessment for this child was submitted <?php if ($time == 0){echo $time;}else{echo $time - 1;}?> Month(s) ago.
<?php } ?>"
src="<?php
if ($record->$period == 0) { echo base_url()."img/warning.png";}
else{
date("M d, Y", strtotime($record->$period));
$vtime = new DateTime($record->$period); ///////////////////////
$today = new DateTime(); // for testing purposes ///Calculate Time period//
$diff = $today->diff($vtime); ///
$time = $diff -> m;
if($time <= 4)
{echo base_url()."img/green.png";}
elseif( $time > 4 && $time <= 6)
{echo base_url()."img/yellow.png";}
elseif($time >= 6)
{echo base_url()."img/red.png";}
}
"
/>
Just like I've said in the comments, you could just separate the logic, make your calculations here and there. After you are done with it, set the variables and then echo it out in the presentation:
<?php
// initialization
$title = '';
$src = '';
// logic
$time = ($time == 0) ? $time : $time - 1;
$title = "Last assessment for this child was submitted %s Month(s) ago."; // initial
if ($record->$period == 0) {
$src = base_url() . "img/warning.png";
// override $title
$title = 'Check record';
} else {
$vtime = new DateTime($record->$period);
$today = new DateTime();
$diff = $today->diff($vtime);
$time = $diff->m;
if($time <= 4) {echo ;
$src = base_url()."img/green.png";
} elseif( $time > 4 && $time <= 6) {
$src = base_url()."img/yellow.png";
} elseif($time >= 6) {
$src = base_url()."img/red.png";
} else {
// whatever you need to do
}
}
$title = sprintf($title, $time);
?>
<!-- HTML MARKUP -->
<img title="<?php echo $title; ?>" src="<?php echo $src; ?>" />
You should avoid putting so much PHP code inline in the HTML to keep your code readable.
if ($record->period === 0) {
echo '<img src="img/warning.png" title="Warning title" />';
} else {
// Are you sure this does what you want?
// You probably need $record->period. (no $)
$vtime = new DateTime($record->$period);
$today = new DateTime();
$diff = $today->diff($vtime);
$time = $diff->m;
$title = 'Last assessment for this child was submitted ' .
($time === 0 ? 0 : $time-1) .
' month(s) ago.';
if ($time <= 4) {
echo '<img src="img/green.png" title="'. $title . '" />';
} else if ($time <= 6) {
// Don't need to check if it's bigger than 4, you've already checked this
// in the initial "if" and if that was succesful, we wouldn't be here.
echo '<img src="img/yellow.png" title="'. $title . '" />';
} else {
echo '<img src="img/red.png" title="' . $title . '" />';
}
}
PHP is easily embed with the HTML. So use it.
$imageURL = "";
if ($record->$period == 0) {
$imageURL = base_url() . "img/warning.png";
} else {
// date("M d, Y", strtotime($record->$period)); // This is not usable remove this statement
$vtime = new DateTime($record->$period); ///////////////////////
$today = new DateTime(); // for testing purposes ///Calculate Time period//
$diff = $today->diff($vtime); ///
$month = $diff->m;
if ($month <= 4) {
$imageURL = base_url() . "img/green.png";
} elseif ($month > 4 && $month <= 6) {
$imageURL = base_url() . "img/yellow.png";
} else {
$imageURL = base_url() . "img/red.png";
}
}
Rewrite your image tag as follow:
<img title = "Last assessment for this child was submitted <?php echo ($time)? $time - 1: $time; ?> Month(s) ago."
src="<?php echo $imageURL; ?>" />
There are some mistakes with your code.Kindly check the below points for further developments.
date("M d, Y", strtotime($record->$period)) : Why this statement is there as you have not saved the result saved by the date function.
$vtime : What is vtime ? Variable should I short and meaningful name.
$diff->m : This will return the month number so to be more specific instead of $time use $month as variable name to store the month value.
Regarding the if condition
First If : checking for $month is <= 4 : correct
Second If: checking for $month > 4 or <=6
Third elseif : in your old code. Why we need this because if it is not
satisfied by above two conditions then that means it is compulsory >= 6
then put this in else part directly.
I have a website that reads data about baseball games. First the website displays the game dates and scores:
$.post('../php/getGameDates.php', function(returnedDates) {
var objDates = jQuery.parseJSON( returnedDates );
$('#content').hide();
var pubStr = "";
for (var a=0; a<objDates.length; a++) {
var dateParts = objDates[a].game_date.split("-");
var mo;
switch(dateParts[1]) {
case "04":
mo = "April"
break;
case "05":
mo = "May"
break;
case "06":
mo = "June"
break;
case "07":
mo = "July"
break;
case "08":
mo = "Aug."
break;
case "09":
mo = "Sept."
break;
case "10":
mo = "Oct."
break;
default:
break;
}
var day = dateParts[2].replace(/^0+/, '');
pubStr += "<div class='game_to_click' id='" + objDates[a].game_date + "'>" + mo + " " + day + ", " + dateParts[0] + ": " + objDates[a].score + "</div>"
}
$('#game_dates').append(pubStr);
...
});
When you click a date, you get a popup of data about that game. There are prev/next buttons on the popup. The thing is, the data seems to "blink" when it appears on the popup. I suspect that's because of the query to the database.
Here is the php code for the "prev" button:
<?php
include_once ('../../../homicide/php/constants_test.php');
// connect to database
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); //open db conn
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit();
}
//date_default_timezone_set('America/New_York');
$thisDate = $_POST['thisDate'];
//echo $thisDate;
//$time = strtotime($thisDate . ' - 1 day');
//$newDate = date('Y-m-d',$time);
$parts = explode("-", $thisDate);
$day = $parts[2];
if (substr($day, -2) == "0") {
$day = substr($day, -1);
$day = intval($day);
}
$day--;
$newDate = $parts[0] . "-" . $parts[1] . "-";
//echo '$day: ' . $day;
if (strlen($day) < 2){
$newDate .= "0";
}
$newDate .= $day;
//echo "new: " . $newDate . " ";
tryQuery($newDate, $mysqli);
function tryQuery($thisDate, $mysqli) {
$q = "SELECT * FROM pirates_games where game_date = '" . $thisDate . "'";
$result = $mysqli->query($q);
$row_cnt = mysqli_num_rows($result);
//echo $row_cnt;
if ($row_cnt > 0) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$arrGame = $row;
}
echo json_encode($arrGame);
mysqli_close($mysqli);
}
else {
//echo 'date on entry: ' . $thisDate . " ";
$parts = explode("-", $thisDate);
$day = $parts[2];
if (substr($day, -2) == "0") {
$day = substr($day, -1);
$day = intval($day);
}
$day--;
$newDate = $parts[0] . "-" . $parts[1] . "-";
//echo '$day: ' . $day;
if (strlen($day) < 2){
$newDate .= "0";
}
$newDate .= $day;
//echo "new: " . $newDate . " ";
//$time = strtotime($thisDate . ' - 1 day');
//$newDate = date('Y-m-d',$time);
//echo "new: " . $newDate;
tryQuery($newDate, $mysqli);
}
}
?>
Is this method of trying first one query then another the right way to go about this? Most times, there is a game the next day or the previous day, but sometimes, the dates skip a day. I'm not sure how to account for skipped days when I try to find the next or previous game.
My way of thinking on this would be to load the games as a sequential rather than a date based method. Then you could recode to show previous 'game' rather than 'previous day's game', (or next day's game) etc... It's more accurate to the game sequence you've described. This way the previous game's date is just associated information, but it could easily be part of the display.
If that doesn't appeal to you, you could load the dates into an array with the associated games (date being the key and game or no game being the data). On dates that have no game you can show that in your display options.
I didn't articulate my problem very well, but I was having two problems at once. Part of the problem was click events firing multiple times, for both the next and prev buttons (See
jQuery click events firing multiple times):
$(".next").unbind().click(function() {
//Stuff
});
$(".prev").unbind().click(function() {
//Stuff
});
The other part of the problem was finding what the next or previous date was, and here, #glennw (below) was correct.
So! Basically I have a database with a load of blog posts, these are all sorted by a UNIX timestamp, and what I need is a way to make this code spit out headers when appropriate, so that it will output something like this:
2008
November
Title 1 - Date Goes Here
Title 2 - Date Goes Here
December
Title 3 - Date Goes Here
2009
January
Title 4 - Date Goes Here
etcetera
Here's my code so far, it works until the comparison of the year, and I still need to come up with a good way of how to make it compare months in a sensible fashion, so that January indeed comes after December, and not some ludicrous 13th month.
[code]
<?php
if ($db = new PDO('sqlite:./db/blog.sqlite3')) {
$stmt = $db->prepare("SELECT * FROM news ORDER BY date DESC");
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$current_year = date("Y", $row[1]);
$current_month = date("m", $row[1]);
if ($current_year > $last_year) {
echo "<h1>" . $current_year . "</h1>";
$last_year = $current_year;
}
echo "<tr>";
echo "<td align='left'><a href='view_post.php?post_id=". $row[1] ."'>" . $row['0'] . " - " . date("Y-m-d, H:i:s", $row[1]) . "</a></td>";
echo "</tr>";
}
}
} else {
die($sqliteerror);
}
?>
[/code]
With unix timestamps you could do something like (pseudo code obviously)
prev_month = null
prev_year = null
foreach results as r
new_month = date('F', r[timestamp]);
new_year = date('Y', r[timestamp]);
if(prev_month != new_month)
//display month
/if
if(prev_year != new_year)
//display year
/if
// display other info
prev_month = new_month
prev_year = new_year
/foreach
<?php
if ($db = new PDO('sqlite:./db/blog.sqlite3')) {
$stmt = $db->prepare("SELECT * FROM news ORDER BY date DESC");
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$current_year = date("Y", $row[1]);
$current_month = date("n", $row[1]); # n instead of m
if ($current_year > $last_year) {
echo "<h1>" . $current_year . "</h1>";
echo "<h2>" . $current_month . "</h2>";
$last_year = $current_year;
$last_month = $current_month;
}
elseif ($current_month > $last_month) {
echo "<h2>" . $current_month . "</h2>";
$last_month = $current_month;
}
echo "<tr>";
echo "<td align='left'><a href='view_post.php?post_id=". $row[1] ."'>" . $row['0'] . " - " . date("Y-m-d, H:i:s", $row[1]) . "</a></td>";
echo "</tr>";
}
}
} else {
die($sqliteerror);
}
?>
I did not test it.
Idea:
If the year changes, also the month changes.
The check for the next month happens only if there is not a change of the year, which is the only case where lastmonth might be bigger than currentmonth.
I would be tempted to do this in two steps, separating the database fetching from the display/html logic, for example:
<?php
//snip
//make big array of archive
$archive = array();
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$year = date("Y", $row[1]);
$month = date("m", $row[1]);
if (!isset($archive[$year])) {
$archive[$year] = array();
}
if (!isset($archive[$year][$month])) {
$archive[$year][$month] = array();
}
$archive[$year][$month][] = $row;
}
//snip
//loop over array and display items
?>
<?php foreach ($achive as $year => $months): ?>
<h1><?php echo $year; ?></h1>
<?php foreach ($months as $month => $posts): ?>
<h2><?php echo $month; ?></h2>
<ul>
<?php foreach ($posts as $post): ?>
<li><?php echo $post[0]; ?> etc...</li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
<?php endforeach; ?>
You should get the years and the months in reverse order as per your SQL query. I haven't tested this, but it should be vaguely correct.