I want to include php variable $i to a function name having parameters
for($i=1; $i<=50; $i++) {
$currentMonth = date("F");
/* draws a calendar */
function draw_calendar($month,$year,$per_day_chu){
$currentDayOfMonth = date("j");
/* draw table */
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
/* table headings */
$headings = array('Su','Mo','Tu','Wed','Th','Fr','Sa');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
/* days and weeks vars now ... */
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
/* row for week one */
$calendar.= '<tr class="calendar-row">';
return $calendar;
}
echo $currentMonth.", ".date("Y");
echo draw_calendar(date("m"), date("Y"), $per_day_chu);
}
in the above code I want to make the function name as function draw_calendar$i($month,$year,$per_day_chu){ and function call as echo draw_calendar(date("m"), date("Y"), $per_day_chu);
Is there any way to achieve this. I have no idea how to set this up. Thankyou.
You should put your function outside of your loop, and then make the call into your loop.
I think you need to do this actually:-
for($i=1; $i<=50; $i++) {
$currentMonth = date("F");
echo $currentMonth.", ".date("Y");
echo draw_calendar(date("m"), date("Y"), $per_day_chu);
}
function draw_calendar($month,$year,$per_day_chu){
$currentDayOfMonth = date("j");
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
$headings = array('Su','Mo','Tu','Wed','Th','Fr','Sa');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
$calendar.= '<tr class="calendar-row">';
return $calendar;
}
Note:-
function code inside loop is wrong practice.
Also check that $per_day_chu will be available every-time inside your for loop and have some correct value each time.
Related
Sorry if there is theme like this, but i didn't find solution for my problem. So let's go... =)(I'm starting to learn php).
This is calendar of events and it will be widget for WP. It need to work onclick event. All code written in one file(this is plugin). In widget(in right sidebar) i write phpcode(for testing) where i call this functions.
http://herytire.esy.es/calendar
You can push '2' or '5' dates, there is data in mysql for these dates.
All works fine, but i never work with php in wordpress, and have problems with this code.
The problem is:
When i use this code in simple html page, you can see it at link above, all works fine, I get results for day that I click, BUT in wp, alert(for error), returns undefined. Two days I'm trying to fix this problem, but nothing. I hope somebody can help me please..!
**admin-ajax.php is done for view side of wp!
<script type="text/javascript"> // ajaxurl in header.php
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
/*
Plugin Name: Release Dates
Description: Small calendar for serials release dates.
Author: J_J
Version: 1.0
*/
function draw_calendar($month, $year) // creating calendar
{
$month = date('m');
$year = date('y');
$calendar = '<table class="calendar">';
$headings = array('S', 'M', 'T', 'W', 'T', 'F', 'S');
$calendar .= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">', $headings).'</td></tr>';
$running_day = date('w', mktime(0, 0, 0, $month, 1, $year));
$days_in_month = date('t', mktime(0, 0, 0, $month, 1, $year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
$calendar .= '<tr class="calendar-row">';
for ($x = 0; $x < $running_day; ++$x) {
$calendar .= '<td class="calendar-day-np"> </td>';
++$days_in_this_week;
}
for ($list_day = 1; $list_day <= $days_in_month; ++$list_day) {
$calendar .= '<td class="calendar-day"><div class="day-number"><a style="cursor:pointer;" onClick="relDaySerial('.$list_day.');">'.$list_day.'</a></div></td>';
if ($running_day == 6) {
$calendar .= '</tr>';
if (($day_counter + 1) != $days_in_month) {
$calendar .= '<tr class="calendar-row">';
}
$running_day = -1;
$days_in_this_week = 0;
}
++$days_in_this_week;
++$running_day;
++$day_counter;
}
if ($days_in_this_week < 8) {
for ($x = 1; $x <= (8 - $days_in_this_week); ++$x) {
$calendar .= '<td class="calendar-day-np"> </td>';
}
}
$calendar .= '</tr>'.'</table>';
return $calendar; }
function get_serials($day) { // here i catch relDaySerial:id
if ($_POST['relDaySerial'] === null) {
$day = date('d');
} else {
$day = $_POST['relDaySerial'];
}
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM tvt_calendar WHERE day=$day");
foreach ($result as $value) {
echo "
<table id='cal-data'>
<tr>
<td class='calendar-day-head'>TV Show</td>
<td class='calendar-day-head'>S</td>
<td class='calendar-day-head'>E</td>
</tr>
<tr class='cal-content'>
<td><a href='#'>".$value->title.'</a></td>
<td>'.$value->season.'</td>
<td>'.$value->series.'</td>
</tr>
</table>
';
}}
function my_action_javascript() {
?>
<script type="text/javascript" >
function relDaySerial(id) {
jQuery.ajax({
type:'POST',
url:ajaxurl,
data:{relDaySerial:id},
success:function(data) {
if(relDaySerial.type == "success") {
jQuery('#cal-bottom').html(data)
}
else {
alert()
}
}});}
</script>
<?php}
add_action('wp_footer', 'my_action_javascript');
add_action('wp_ajax_my_action_javascript', 'my_action_javascript');
add_action('wp_ajax_nopriv_my_action_javascript', 'my_action_javascript');?>
Because your alert() requires a parameter.
Try with this:
alert('An error has occurred.');
I'm trying to build an events calendar in PHP and SQL based on an example by David Walsh. His example is quite old and uses functions like mysql_query which are deprecated so I have tried to modernise using PDO. So far I've managed to print out the calendar and am able to select different months and years. I've also successfully created a database connection. The table consists of an id (Auto incremented), title (varchar) and event_date(date). I've populated the table with a few events but I can't seem to retrieve them successfully. I've included the most relevant parts of the code at the top but I've copied the whole code over for context.
My query to the database
$events = array();
try { $results = $db->query("SELECT title, DATE_FORMAT(event_date,'%Y-%m-%d') AS event_date FROM events WHERE event_date LIKE '$year-$month'");
echo "<pre>";
var_dump($results);
} catch (Exception $e) {
echo "cannot get results!";
exit;
}
$bookings = $results->fetchAll(PDO::FETCH_ASSOC);
while($row = $bookings) {
$events[$row['event_date']][] = $row;
}
echo '<pre>';
var_dump($bookings);
Result from my var_dump on $results
object(PDOStatement)#2 (1) {
["queryString"]=>
string(105) "SELECT title, DATE_FORMAT(event_date,'%Y-%m-%d') AS event_date FROM events WHERE event_date LIKE '2014-1'"
}
var_dump on $bookings says that my array is empty
array(0) {
}
Full code for context
<?php
require('database.php');
/* draws a calendar */
function draw_calendar($month,$year,$events = array()){
/* draw table */
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
/* table headings */
$headings = array('Sontag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
/* days and weeks vars now ... */
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
/* row for week one */
$calendar.= '<tr class="calendar-row">';
/* print "blank" days until the first of the current week */
for($x = 0; $x < $running_day; $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
$days_in_this_week++;
endfor;
/* keep going with days.... */
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
$calendar.= '<td class="calendar-day"><div style="position:relative;height:100px;">';
/* add in the day number */
$calendar.= '<div class="day-number">'.$list_day.'</div>';
$event_day = $year.'-'.$month.'-'.$list_day;
if(isset($events[$event_day])) {
foreach($events[$event_day] as $event) {
$calendar.= '<div class="event">'.$event['title'].'</div>';
}
}
else {
$calendar.= str_repeat('<p> </p>',2);
}
$calendar.= '</div></td>';
if($running_day == 6):
$calendar.= '</tr>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<tr class="calendar-row">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
/* finish the rest of the days in the week */
if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
endfor;
endif;
/* final row */
$calendar.= '</tr>';
/* end the table */
$calendar.= '</table>';
/** DEBUG **/
$calendar = str_replace('</td>','</td>'."\n",$calendar);
$calendar = str_replace('</tr>','</tr>'."\n",$calendar);
/* all done, return result */
return $calendar;
}
function random_number() {
srand(time());
return (rand() % 7);
}
/* date settings */
$month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
$year = (int) ($_GET['year'] ? $_GET['year'] : date('Y'));
/* select month control */
$select_month_control = '<select name="month" id="month">';
for($x = 1; $x <= 12; $x++) {
$select_month_control.= '<option value="'.$x.'"'.($x != $month ? '' : ' selected="selected"').'>'.date('F',mktime(0,0,0,$x,1,$year)).'</option>';
}
$select_month_control.= '</select>';
/* select year control */
$year_range = 7;
$select_year_control = '<select name="year" id="year">';
for($x = ($year-floor($year_range/2)); $x <= ($year+floor($year_range/2)); $x++) {
$select_year_control.= '<option value="'.$x.'"'.($x != $year ? '' : ' selected="selected"').'>'.$x.'</option>';
}
$select_year_control.= '</select>';
/* "next month" control */
$next_month_link = 'Next Month >>';
/* "previous month" control */
$previous_month_link = '<< Previous Month';
/* bringing the controls together */
$controls = '<form method="get">'.$select_month_control.$select_year_control.' <input type="submit" name="submit" class="btn btn-default" value="Go" /> '.$previous_month_link.' '.$next_month_link.' </form>';
/* get all events for the given month */
$events = array();
try { $results = $db->query("SELECT title, DATE_FORMAT(event_date,'%Y-%m-%d') AS event_date FROM events WHERE event_date LIKE '$year-$month'");
echo "<pre>";
var_dump($results);
} catch (Exception $e) {
echo "cannot get results!";
exit;
}
$bookings = $results->fetchAll(PDO::FETCH_ASSOC);
while($row = $bookings) {
$events[$row['event_date']][] = $row;
}
echo '<pre>';
var_dump($bookings);
echo '<h2 style="float:left; padding-right:30px;">'.date('F',mktime(0,0,0,$month,1,$year)).' '.$year.'</h2>';
echo '<div style="float:left;">'.$controls.'</div>';
echo '<div style="clear:both;"></div>';
echo draw_calendar($month,$year,$events);
echo '<br /><br />';
Besides the LIKE issue
FetchAll get the entire set,so while wont work.Use foreach
foreach ($bookings as $row) {
$events[$row['event_date']][] = $row;
}
Also in your while you use the assignment operator instead of the comparison ==
I think you forgot a wildcard in your sql query string.
You can try this:
WHERE event_date LIKE '$year-$month%'"
You will do much better if you handle your event_date column as a date rather than as a text field.
Try this query:
SELECT title,
DATE_FORMAT(event_date,'%Y-%m-%d') AS event_date
FROM events
WHERE event_date >= DATE(DATE_FORMAT(NOW(),'%Y-%m-01'))
AND event_date < DATE(DATE_FORMAT(NOW(),'%Y-%m-01')) + INTERVAL 1 MONTH
This will find all the event_date values in the present month, and at the same time will use the MySQL index on event_date for searching if you have one.
If you want last month's events, you can do this instead.
WHERE event_date >= DATE(DATE_FORMAT(NOW(),'%Y-%m-01')) - INTERVAL 1 MONTH
AND event_date < DATE(DATE_FORMAT(NOW(),'%Y-%m-01'))
Here's an introduction to this topic.
http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
I am working on a simple event calendar. When I first load the page the calendar loads. Then when I click next or previous it takes me to the next month but the events do not load and the month headings do not change but the correct calendar is drawn. I tried taking my event script from the code and putting it in the function that controls the ajax but it didn't work.
Here is a link to the page.
http://hartslogmuseum.com/bookhjr10/cal/final/ajcal3.php
(Yes its ugly for now)
Could someone point me in the right direction. Thanks.
Here is the code.
<?php
/* Open up a connection to the mysql database on the same server as website */
$dbhost = '';
$dblogin = '';
$dbpass = '!';
$dbbase = '';
$conn = mysql_connect($dbhost, $dblogin, $dbpass, $dbbase)
or die("Unable to connect to mysql database");
function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
$_SERVER ['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
if(isAjax() && isset($_POST['month']))
{
$month = $_POST['month'];
$year = !isset($_POST['year']) ? date('Y', $current_time) : $_POST['year'];
$events = array();
die(draw_calendar($month,$year,$events));
die(draw_calendar($month,$year,$events));
}
/* Select our database (there is more than one in my server) */
mysql_select_db("", $conn);
/* draws a calendar */
function draw_calendar($month,$year,$events = array()){
echo '<div id="calendar_wrapper">';
/* draw table */
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
/* table headings */
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
/* days and weeks vars now ... */
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
/* row for week one */
$calendar.= '<tr class="calendar-row">';
/* print "blank" days until the first of the current week */
for($x = 0; $x < $running_day; $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
$days_in_this_week++;
endfor;
/* keep going with days.... */
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
$calendar.= '';
/* add leading zero in the day number */
if($list_day < 10) {
$list_day = str_pad($list_day, 2, '0', STR_PAD_LEFT);
}
/* add leading zero in the month number */
if($month < 10) {
$month = str_pad($month, 2, '0', STR_PAD_LEFT);
}
$event_day = $year.'-'.$month.'-'.$list_day;
$calendar.= '<td class="calendar-day"><div style="position:relative;height:100px;">';
/* add in the day number */
$calendar.= '<div class="day-number">'.$list_day.'</div>';
$event_day = $year.'-'.$month.'-'.$list_day;
if(isset($events[$event_day])) {
foreach($events[$event_day] as $event) {
$calendar.= '<div class="event">'.$event['title'].'</div>';
}
}
else {
$calendar.= str_repeat('<p> </p>',2);
}
$calendar.= '</div></td>';
if($running_day == 6):
$calendar.= '</tr>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<tr class="calendar-row">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
/* finish the rest of the days in the week */
if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
endfor;
endif;
/* final row */
$calendar.= '</tr>';
/* end the table */
$calendar.= '</table>';
/** DEBUG **/
$calendar = str_replace('</td>','</td>'."\n",$calendar);
$calendar = str_replace('</tr>','</tr>'."\n",$calendar);
/* all done, return result */
return $calendar;
}
function random_number() {
srand(time());
return (rand() % 7);
}
/* date settings */
$month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));
$year = (int) ($_GET['year'] ? $_GET['year'] : date('Y'));
/* "next month" control */
$next_month_link = 'Next »';
$heading ='<td colspan=5 class="month">$month_name $year</b></td>';
/* "previous month" control */
$previous_month_link = '« Prev';
/* bringing the controls together */
$controls = '<form method="get">'.$select_month_control.$select_year_control.$previous_month_link.$heading.' '.$next_month_link.' </form>';
/* get all events for the given month
I had to rewrite this query to get
anything usable out of the mysql
database we already had. */
$events = array();
$query = ("
SELECT
event_title
AS title,
DATE_FORMAT( FROM_UNIXTIME(event_date), '%Y-%m-%d' )
AS event_date
FROM
events
WHERE
FROM_UNIXTIME(event_date)
LIKE '$year-%$month-%'");
/* verify the query is correct
echo $query;
echo "<hr />";
echo "<br />";
*/
$result = mysql_query($query,$conn) or die('error 2');
while($row = mysql_fetch_assoc($result)) {
$events[$row['event_date']][] = $row;
/* verify that the query gets results.
Also generates a list of this months events*/
/*echo $row['event_title']." ----- ".$row['event_date'];
echo "<br />";*/
}
echo '<h2 style="float:left; padding-right:30px;">'.date('F',mktime(0,0,0,$month,1,$year)).' '.$year.'</h2>';
echo '<div style="float:left;">'.$controls.'</div>';
echo '<div style="clear:both;"></div>';
echo draw_calendar($month,$year,$events);
echo '<br /><br />';
echo '</div>';
?>
<html>
<head>
<link href="cal.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="proto.js"></script>
<script type="text/javascript" language="javascript">
var current_month = <?PHP echo $month ?>;
var current_year = <?PHP echo $year ?>;
function getPrevMonth()
{
if(current_month == 1)
{
current_month = 12;
current_year = current_year - 1;
}
else
{
current_month = current_month - 1;
}
params = 'month='+current_month+'&year='+current_year;
new Ajax.Updater('calendar_wrapper',window.location.pathname,{method:'post',parameters: params});
}
function getNextMonth()
{
if(current_month == 12)
{
current_month = 1;
current_year = current_year + 1;
}
else
{
current_month = current_month + 1;
}
params = 'month='+current_month+'&year='+current_year;
new Ajax.Updater('calendar_wrapper',window.location.pathname,{method:'post',parameters: params});
}
</script>
</head>
<body>
<div id="calendar_wrapper"><? /*?PHP draw_calendar($month,$year,$events = array());*/ ?>
</body>
</html>
your posted code doesn't seen to include the portion where '$month_name' is defined. The issue is relat ed (most likely) to $month_name not being set properly. Look to do something like:
function draw_calendar($month,$year,$events = array()){
//set month name
$month_name = date("F", mktime(0, 0, 0, $month, 10));
//rest of your code
Okay, I'm a newbie with jQuery and PHP, but here's a couple things I noticed:
1) You're creating a second "calendar_wrapper" div each time you reload the page after calling your getNextMonth() or getPrevMonth(). I wasn't familiar with Ajax.Updater, and Google shows that it's Prototype.js, not jQuery, right? To resolve that, my guess would be that you're not referring to the calendar_wrapper using DOM syntax in the Ajax.Updater. Try "#calendar_wrapper" in your Ajax.Updater calls inside getNextMonth()/getPrevMonth(). If you're looking for the jQuery equivalent to Ajax.Updater, check out $.ajax().
2) Your "date settings" section has your variables looking in the GET global array ($_GET['month']), but your AJAX updater is sending the data via POST. This could be why your PHP script is returning the data properly, but not updating the variables properly.
3) I didn't see anything in your code to select the month/year elements and update them with the data received from your getPrevMonth() or getNextMonth(). For this, you'd probably need an event handler to update the elements with the new data. For example, I'd give your first h2 header an id, then have jQuery update the $.text() inside the h2 with the data received from your PHP. However, it looks like you're seeking to have PHP echo out the updated HTML when it reads the updated $month variable. If this is the case, hopefully resolving the page making two calendar_wrapper divs will resolve it.
This code creates a nice calendar (original code), but I'm trying to make some modifications on it.
The first lines are ok, no need to pay attention to that, but here it is:
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
$calendar.= '<tr class="calendar-row">';
for($x = 0; $x < $running_day; $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
$days_in_this_week++;
endfor;
Here is where I stucked. From now on, the calendar access the database and print my dates based on the events I have recorded. For the dates that the query has found any event, than the code prints a link in it. See the code:
$db = new PDO('mysql:host=localhost;dbname=calendar','root','');
$stmt = $db->prepare('SELECT time, title FROM events');
$stmt->execute();
$rawTimeStamps = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cleanDateArray = array();
foreach ($rawTimeStamps as $t) {
$rawDate = $t['time'];
$rawDate = getdate($rawDate);
$cleanDate = mktime(0,0,0,$rawDate['mon'],$rawDate['mday'],$rawDate['year']);
$cleanDataArray[] = $cleanDate;
}
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
$calendar.= '<td class="calendar-day">';
$timestamp = mktime(0,0,0,$month,$list_day,$year);
if (in_array($timestamp, $cleanDataArray)) {
$calendar.= '<div class="day-number day-number-event">'.$list_day.'</div>';
} else {
$calendar.= '<div class="day-number day-number-noevent">'.$list_day.'</div></div><div id="calendar-events"></div>';
}
$calendar.= '</td>';
if($running_day == 6):
$calendar.= '</tr>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<tr class="calendar-row">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
And than, the code finishes the calendar.
if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
endfor;
endif;
$calendar.= '</tr>';
$calendar.= '</table>';
return $calendar;
What I need is to print other infos from the database related to the date that has an event. In other words, all I want is to print the events title (that are also recorded in a column of the events table) right below the event data. Something like:
$calendar.= '<div class="day-number day-number-event"><a id="'.$timestamp.'" href="#">'.$list_day.'</a></div><p>'.$title.'</p>';}
After some tests and studies, this is the solution:
function draw_calendar($month,$year){
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
/* days and weeks vars now ... */
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
/* row for week one */
$calendar.= '<tr class="calendar-row">';
/* print "blank" days until the first of the current week */
for($x = 0; $x < $running_day; $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
$days_in_this_week++;
endfor;
$db = new PDO('mysql:host=localhost;dbname=calendar','root','');
$stmt = $db->prepare('SELECT time, title FROM events');
$stmt->execute();
$rawTimeStamps = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cleanDateArray = array();
foreach ($rawTimeStamps as $t) {
$rawDate = $t['time'];
$rawDate = getdate($rawDate);
$cleanDate = mktime(0,0,0,$rawDate['mon'],$rawDate['mday'],$rawDate['year']);
$cleanDataArray[] = $cleanDate;
}
/* keep going with days.... */
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
$calendar.= '<td class="calendar-day">';
$timestamp = mktime(0,0,0,$month,$list_day,$year);
if (in_array($timestamp, $cleanDataArray)) {
/* embromation */
$date = getdate($timestamp);
$time_start = mktime(0,0,0,$date['mon'],$date['mday'],$date['year']);
$time_end = mktime(23,59,59,$date['mon'],$date['mday'],$date['year']);
$stmt = $db->prepare('SELECT title FROM events WHERE time BETWEEN ? AND ?');
$stmt->bindParam(1,$time_start,PDO::PARAM_INT);
$stmt->bindParam(2,$time_end,PDO::PARAM_INT);
$stmt->execute();
$events = $stmt->fetch(PDO::FETCH_ASSOC);
$calendar.= '<div class="day-number day-number-event">'.$list_day.'</div><p>'.$events["title"].'</p>';
} else {
$calendar.= '<div class="day-number day-number-noevent">'.$list_day.'</div></div><div id="calendar-events"></div>';
}
$calendar.= '</td>';
if($running_day == 6):
$calendar.= '</tr>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<tr class="calendar-row">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
/* finish the rest of the days in the week */
if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
endfor;
endif;
/* final row */
$calendar.= '</tr>';
/* end the table */
$calendar.= '</table>';
/* all done, return result */
return $calendar;
}
I have a php MySql booking calendar, which shows whether the room is booked or not on a date basis. The problem is, it shows the wrong info. For example, if I book 5-6 it should have marked the 5th red, meaning it was booked on 5th. It shows 6th but by 6, 12:00:00 the room will be free. Another example: If I book 23-25 it shows 24, 25 as booked, but it should show 23-25, dont know where the problem is.
Here is the code:
function getAllRooms($date,$month,$year)
{
global $db;
$where = ' ';
if ($_GET['room_type'] != '') {
$where .= " HAVING room_type = '".$_GET['room_type']."'";
}
$sql = "SELECT room_type
FROM
room
GROUP BY
room_type
$where
";
/*echo $sql;
exit;*/
$result = $db->Execute($sql);;
$room = '';
while (!$result->EOF) {
$qs = '?room_type='.$result->fields('room_type').'&month='.$month.'&year='.$year;
$total = get_total_rooms_by_type($result->fields('room_type'),$date,$month,$year);
$room .=
'<div class="'.$result->fields('room_type').'">
<a href="'.BASE_URL.'room_detail.php'.$qs.'">
'.$result->fields('room_type').' ('.$total.')
</a>
</div>';
$result->MoveNext();
}
$result->Close;
return $room;
}
function get_total_rooms_by_type($room_type,$date,$month,$year)
{
global $db;
$_newdate = $year.'-'.$month.'-'.$date;
$sql = "SELECT room_id FROM room where room_type = '$room_type' ";
$room_results = $db->Execute($sql);
$room_ids = array();
while (!$room_results->EOF) {
$room_ids[] = $room_results->fields('room_id');
$room_results->MoveNext();
}
$room_results_str = implode(',',$room_ids);
$where = ' where 1 = 1 ';
$available = 1;
if ($_GET['booking_status'] == '1') {
$where .= ' and (booking_status = 1 or booking_status = 2)';
$available = 0;
} else if ($_GET['booking_status'] == '2') {
$where .= ' and (booking_status = 2)';
$available = 0;
}
$sql = "select count(room_id) from bookings
$where
and checkin <= '$_newdate'
and '$_newdate' <= checkout
and room_id in ($room_results_str)
";
if ($available == 0) {
return $db->GetOne($sql);
} else {
return count($room_ids) - $db->GetOne($sql);
}
}
function draw_calendar_room($month,$year){
/* draw table */
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
/* table headings */
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
/* days and weeks vars now ... */
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
/* row for week one */
$calendar.= '<tr class="calendar-row">';
/* print "blank" days until the first of the current week */
for($x = 0; $x < $running_day; $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
$days_in_this_week++;
endfor;
/* keep going with days.... */
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
$calendar.= '<td class="calendar-day">';;
$calendar.= '<div class="day-number" style=" padding:5px 5px 45px;background-color:'.getRoomColor($list_day,$month,$year).'">'.$list_day.'</div>';
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$calendar.= '</td>';
if($running_day == 6):
$calendar.= '</tr>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<tr class="calendar-row">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
/* finish the rest of the days in the week */
if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
endfor;
endif;
/* final row */
$calendar.= '</tr>';
/* end the table */
$calendar.= '</table>';
/* all done, return result */
return $calendar;
}
function getRoomColor($date,$month,$year)
{
global $db;
$where = ' ';
if ($_GET['room_id'] != '') {
$room_id = $_GET['room_id'];
} else {
$sql = "SELECT room_id
FROM
room
WHERE
room_type = '".$_GET['room_type']."' order by room_number asc
";
$room_id = $db->GetOne($sql);;
}
$_newdate = "$year-$month-$date";
$sql = "SELECT booking_status
FROM
bookings
where
checkin <= '$_newdate'
and
'$_newdate' <= checkout
and
room_id = '$room_id'
";
/*echo $sql;
exit;*/
$result = $db->GetOne($sql);;
if ($result == 1) {
return '#FF0';
} else if ($result == 2) {
return '#F00';
} else {
return '#64C733';
}
}
Sorry, not much of an answer but..
Well I can go through your code but I am sure you can solve this problem yourself since
its just logic error I believe.
What you can do is print the all the resulting variable from beginning and
debug through them. That way you will know which line is giving problem.
You can then try to solve it yourself or ask a more precise question here.
Good Luck! :)
it was actually issue of time mismatch. In db I set date time as checkin and checkout but my checking sql retrieving data with date there were no time consideration.
now added:
$_newdate = $year.'-'.$month.'-'.$date . " " . "12:00:00";
is working like a charm. !!!!