Working Sql query and working calendar How do i combine them?

I have a working query that pulls all appointments in the table for the day. I have a working calendar that builds the month and highlights the current day. I want to add the query to the calendar and just count the number of appointments for each day and show the number under the day of the month. The calendar is from a tutorial I found online. Any help is much appreciated.

Query I currently use to pull appointments for the current day.


$sql = <<<SQL
  SELECT client.lastName, client.firstName, dog.name, appointments.start, appointments.appointmentId, appointments.complete, client.clientId, dog.dogId
FROM appointments LEFT JOIN client ON appointments.clientId = client.clientId
LEFT JOIN dog ON appointments.dogId = dog.dogId
WHERE appointments.start > CURDATE()
ORDER BY appointments.start ASC
SQL;

if(!$result = $db->query($sql)){
    die('There was an error while running the query [' . $db->error . ']');
}
	
	 $num_rows = $result->num_rows;

Calendar I am trying to use.


<?php
date_default_timezone_set('America/Denver');
function build_calendar($month,$year,$dateArray) {
$today_date = date("d");
$today_date = ltrim($today_date, '0');

     // Create array containing abbreviations of days of week.
     $daysOfWeek = array('Sun','Mon','Tue','Wed','Thr','Fri','Sat');

     // What is the first day of the month in question?
     $firstDayOfMonth = mktime(0,0,0,$month,1,$year);

     // How many days does this month contain?
     $numberDays = date('t',$firstDayOfMonth);

     // Retrieve some information about the first day of the
     // month in question.
     $dateComponents = getdate($firstDayOfMonth);

     // What is the name of the month in question?
     $monthName = $dateComponents['month'];

     // What is the index value (0-6) of the first day of the
     // month in question.
     $dayOfWeek = $dateComponents['wday'];

     // Create the table tag opener and day headers

     $calendar = "<table border='1px'>";
     $calendar .= "<caption>$monthName $year</caption>";
     $calendar .= "<tr>";

     // Create the calendar headers

     foreach($daysOfWeek as $day) {
          $calendar .= "<th class='header' width='50px' height='50px'>$day</th>";
     }

     // Create the rest of the calendar

     // Initiate the day counter, starting with the 1st.

     $currentDay = 1;

     $calendar .= "</tr><tr>";

     // The variable $dayOfWeek is used to
     // ensure that the calendar
     // display consists of exactly 7 columns.

     if ($dayOfWeek > 0) {
          $calendar .= "<td colspan='$dayOfWeek' width='50px' height='50px'>&nbsp;</td>";
     }

     $month = str_pad($month, 2, "0", STR_PAD_LEFT);

      while ($currentDay <= $numberDays) {

          // Seventh column (Saturday) reached. Start a new row.

          if ($dayOfWeek == 7) {

               $dayOfWeek = 0;
               $calendar .= "</tr><tr>";

          }

          $currentDayRel = str_pad($currentDay, 2, "0", STR_PAD_LEFT);

          $date = "$year-$month-$currentDayRel";
		
	  if($currentDayRel == $today_date ){  $calendar .= "<td class='day' id='today_date ' rel='$date' width='50px' height='50px' alighn='center' valign='top'align='left'><a href='appointmentdate.php?date=$date'><b>$currentDay</b></a></td>"; }

		  else { $calendar .= "<td class='day' rel='$date' width='50px' height='50px' valign='top' align='left'><a href='appointmentdate.php?date=$date'>$currentDay</a></td>"; }

          // Increment counters

          $currentDay++;
          $dayOfWeek++;

     }



     // Complete the row of the last week in month, if necessary

     if ($dayOfWeek != 7) {

          $remainingDays = 7 - $dayOfWeek;
          $calendar .= "<td colspan='$remainingDays'>&nbsp;</td>";

     }

     $calendar .= "</tr>";

     $calendar .= "</table>";

     return $calendar;

}

?>

<?php
error_reporting(0);
     $dateComponents = getdate();

     $month = $dateComponents['mon']; 			
     $year = $dateComponents['year'];

     echo build_calendar($month,$year,$dateArray);

?>

I have error reporting off because I get an undefined variable $dateArray when I echo build_calendar on the last line of the calendar code. Not sure why I am getting a error.

You’re passing $dateArray into build_calendar but you don’t seem to be defining it anywhere in the code you posted. It’s not actually used anywhere inside the function anyway, so you could just remove it altogether.

As for adding the number of appointments to each day on the calendar, I’d pull the relevant data from the DB like this:


$sql = &lt;&lt;&lt;SQL 
SELECT DAY(`start`) as `day`, count(*) as total
FROM appointments 
WHERE MONTH(`start`) = $month
GROUP BY DATE(`start`)
ORDER BY DATE(`start`) ASC 
SQL;

if(!$result = $db-&gt;query($sql)) { 
    die('There was an error while running the query [' . $db-&gt;error . ']'); 
}

$appointments = array();
while($row = $result-&gt;fetch_assoc()){
   $appointments[ $row["day"] ] = $row['total'];
}

This will give you an array with an entry for each day of the month that has appointments, where the value is the number of appointments that day. Inside the build_calendar function, where it loops through each day, you can check if that day is set in the $appointments and output the number of appointments.

Hi fretburner. Thanks for your help.
When I try adding the sql query to the calendar script I get a couple of errors

SCREAM: Error suppression ignored for
( ! ) Parse error: syntax error, unexpected T_SL in C:\wamp\www\Grooming\include\calendar.php on line 3

If you remember from my last thread I am a complete noob when it comes to php and am doing all of this for fun while I start taking classes to study programming. I am trying to add the sql query to the top of the calendar.php. And then show how many appointments are scheduled for each day even if it is zero. I you don’t mind will you show where in the calendar script you would have the query checking for appointments and then how you would call on that.


if($currentDayRel == $today_date ){  $calendar .= "<td class='day' id='today_date ' rel='$date' width='50px' height='50px' alighn='center' valign='top'align='left'><a href='appointmentdate.php?date=$date'><b>$currentDay</b></a></td>"; }

          else { $calendar .= "<td class='day' rel='$date' width='50px' height='50px' valign='top' align='left'><a href='appointmentdate.php?date=$date'>$currentDay</a></td>"; }

Check to make sure there aren’t any spaces after $sql = <<<SQL as that could be causing the error.

To display the number of appointments when creating the calendar, you could do something like this:


if ( isset($appointments[$currentDay]) ) {
    $app_count = ' ('.$appointments[$currentDay].')';
} else {
    $app_count = '';
}

if($currentDayRel == $today_date ){
    $calendar .= "<td class='day' id='today_date ' rel='$date' width='50px' height='50px' alighn='center' valign='top'align='left'><a href='appointmentdate.php?date=$date'><b>$currentDay</b></a>$app_count</td>";
} else {
    $calendar .= "<td class='day' rel='$date' width='50px' height='50px' valign='top' align='left'><a href='appointmentdate.php?date=$date'>$currentDay</a>$app_count</td>";
} 

Thanks again fretburner! A few miner changes and all is working fine. And of course I still want to add a few things. I want to start figuring out how to add a next/previous month option and next/previous year. I am also stuck on appointmentdate.php where I get the date that I choose from the calendar as “2013-07-23” and how I query the table for all appointments that day the column is DATETIME format. I will see where I get with that and may ask for more help once I think I have it pretty close.

Okay I have what I think should work for viewing all appointments on selected date. Trying to pull all records where start = $date which is formatted like Y-m-d.


$date = new DateTime($_GET['date']);
$sql = <<<SQL
  SELECT client.lastName, client.firstName, dog.name, appointments.start, appointments.appointmentId, appointments.complete, client.clientId, dog.dogId
FROM appointments LEFT JOIN client ON appointments.clientId = client.clientId
LEFT JOIN dog ON appointments.dogId = dog.dogId
WHERE date(appointments.start) = $date
ORDER BY appointments.start ASC
SQL;

Not sure why this is not working.

$date = new DateTime($_GET['date']); 
	$sql = <<<SQL
  SELECT client.lastName, client.firstName, dog.name, appointments.start, appointments.appointmentId, client.clientId, dog.dogId
FROM appointments LEFT JOIN client ON appointments.clientId = client.clientId
LEFT JOIN dog ON appointments.dogId = dog.dogId 
WHERE DATE(appointments.start) = '$date'
ORDER BY appointments.start ASC //line 13 
SQL;

I am getting this error.

Catchable fatal error: Object of class DateTime could not be converted to string in C:\wamp\www\New_Grooming\include\selectedday.php on line 13

Have also tried $date = new Date($_GET[‘date’]);

You need to use the format method of the DateTime object to return a string that you can use in your DB query:


$date = new DateTime($_GET['date']); 
$chosenDate = $date->format('Y-m-d H:i:s');

Thanks fretburner. That worked. Kinda confused though I thought that the DATE(appointments.start) was making it so that the query was only looking at the Y-m-d of each record. Which I guess is still true since when i format $date as $date->format(‘Y-m-d H:i:s’) it ends up 2013-07-25 00:00:00. and obviously only looks at the date when searching the records. But I do get that that now and thanks again!

If you don’t mind, I have also been trying to make it so that you can manually select the month and year on the calendar with no luck. Can you point me in the right direction if it is possible to make the calendar code i have below work this way. I thinking I could have a form at the top where you can select a month and year from dropdown and then see if the values are set before building the calendar but I would rather have a next and previous button. Having no experience this far into php I have ideas of how to go about this but always draw blanks when I actually try to make it happen.


&lt;?php
date_default_timezone_set('America/Denver');

function build_calendar($month,$year) {
$today_date = date("d");
$today_date = ltrim($today_date, '0');


     // Create array containing abbreviations of days of week.
     $daysOfWeek = array('Sun','Mon','Tue','Wed','Thr','Fri','Sat');

     // What is the first day of the month in question?
     $firstDayOfMonth = mktime(0,0,0,$month,1,$year);

     // How many days does this month contain?
     $numberDays = date('t',$firstDayOfMonth);

     // Retrieve some information about the first day of the
     // month in question.
     $dateComponents = getdate($firstDayOfMonth);

     // What is the name of the month in question?
     $monthName = $dateComponents['month'];

     // What is the index value (0-6) of the first day of the
     // month in question.
     $dayOfWeek = $dateComponents['wday'];

     // Create the table tag opener and day headers

     $calendar = "&lt;table border='1px' width='700px'&gt;";
     $calendar .= "&lt;caption&gt;$monthName $year&lt;/caption&gt;";
     $calendar .= "&lt;tr&gt;";

     // Create the calendar headers

     foreach($daysOfWeek as $day) {
          $calendar .= "&lt;th class='header' width='50px' height='75px'&gt;$day&lt;/th&gt;";
     }

     // Create the rest of the calendar

     // Initiate the day counter, starting with the 1st.

     $currentDay = 1;

     $calendar .= "&lt;/tr&gt;&lt;tr&gt;";

     // The variable $dayOfWeek is used to
     // ensure that the calendar
     // display consists of exactly 7 columns.

     if ($dayOfWeek &gt; 0) {
          $calendar .= "&lt;td colspan='$dayOfWeek' width='50px' height='75px'&gt;&nbsp;&lt;/td&gt;";
     }

     $month = str_pad($month, 2, "0", STR_PAD_LEFT);
	 include("include/config.php");
	 $sql = &lt;&lt;&lt;SQL
SELECT DAY(`start`) as `day`, count(*) as total
FROM appointments
WHERE MONTH(`start`) = $month
GROUP BY DATE(`start`)
ORDER BY DATE(`start`) ASC
SQL;

if(!$result = $db-&gt;query($sql)) {
    die('There was an error while running the query [' . $db-&gt;error . ']');
}

$appointments = array();
while($row = $result-&gt;fetch_assoc()){
   $appointments[ $row["day"] ] = $row['total'];
}

      while ($currentDay &lt;= $numberDays) {

          // Seventh column (Saturday) reached. Start a new row.

          if ($dayOfWeek == 7) {

               $dayOfWeek = 0;
               $calendar .= "&lt;/tr&gt;&lt;tr&gt;";

          }
		
		

          $currentDayRel = str_pad($currentDay, 2, "0", STR_PAD_LEFT);

          $date = "$year-$month-$currentDayRel";
		
		  if( isset($appointments[$currentDay])) {
		  $app_count = ' (  '.$appointments[$currentDay].' )';
		  }
		  else {
		  $app_count = '';
		  }
		
	  if($currentDayRel == $today_date ){  $calendar .= "&lt;td class='day' id='today_date ' rel='$date' width='50px' height='75px' alighn='center' valign='top'align='left' bgcolor='#000080'&gt;&lt;a href='appointmentdate.php?date=$date'&gt;&lt;button type='button'&gt;$currentDay&lt;/button&gt;&lt;/a&gt;&lt;br /&gt;$app_count&lt;/td&gt;"; }

		  else { $calendar .= "&lt;td class='day' rel='$date' width='50px' height='75px' valign='top' align='left' bgcolor='#737CA1'&gt;&lt;a href='appointmentdate.php?date=$date'&gt;&lt;button type='button'&gt;$currentDay&lt;/button&gt;&lt;/a&gt;&lt;br /&gt;$app_count&lt;/td&gt;"; }

          // Increment counters

          $currentDay++;
          $dayOfWeek++;

     }



     // Complete the row of the last week in month, if necessary

     if ($dayOfWeek != 7) {

          $remainingDays = 7 - $dayOfWeek;
          $calendar .= "&lt;td colspan='$remainingDays'&gt;&nbsp;&lt;/td&gt;";

     }

     $calendar .= "&lt;/tr&gt;";

     $calendar .= "&lt;/table&gt;";

     return $calendar;

}

?&gt;

&lt;?php

     $dateComponents = getdate();

     $month = $dateComponents['mon']; 			
     $year = $dateComponents['year'];

     echo build_calendar($month,$year);

?&gt;

Any help is very much appreciated.

Yes, you’re right, you could actually do $date->format('Y-m-d') as you’re only comparing against the date.

Your script currently generates a calendar based on the current month. To be able to move back and forth between different months, we can change the script to accept month and year parameters passed in the URL (e.g example.com/appointments.php?month=7&year=2013):


$dateComponents = getdate(); 
if (!$month = filter_input(INPUT_GET, 'month', FILTER_SANITIZE_NUMBER_INT)) {
    $month = $dateComponents['mon'];
}
if (!$year = filter_input(INPUT_GET, 'year', FILTER_SANITIZE_NUMBER_INT)) {
    $year = $dateComponents['year'];
}

Here, I’m using [fphp]filter_input[/fphp] to pull in the values from $_GET, while at the same time filtering out non-numeric values. If the values are non-numeric, or aren’t set, the IF condition will evalute to false, and the current month/year will be set as the default values.

At the end of the build_calendar function, you need to calculate the previous/next values, and add links to the bottom of the table:


$calendar .= "</tr>"; 
 
if ($month == 1) {
    $prevMonth = 12;
    $prevYear = $year -1;
    $nextMonth = 2;
    $nextYear = $year;
} elseif ($month == 12) {
    $prevMonth = $month -1;
    $prevYear = $year;
    $nextMonth = 1;
    $nextYear = $year + 1;
} else {
    $prevMonth = $month -1;
    $prevYear = $year;
    $nextMonth = $month +1;
    $nextYear = $year;
}

$calendar .= "<tr><td colspan='3'><a href='?month=$prevMonth&year=$prevYear'><< Previous</a></td><td></td><td colspan='3'><a href='?month=$nextMonth&year=$nextYear'>Next >></a></td></tr>"; 

$calendar .= "</table>";