Jump to content

Recommended Posts

 

    Good Evening ! 
little help or a lot please ?

I have coded a calendar on my site and am now trying to input the data info from MySQL into the 
calendar by PHP for each corresponding date...the calendar code works but I cant figure out how to 
get the info that's submitted in to the specified/corresponding date in the calendar :/ but I can get 
it to the bottom of the page.

I've been at this 3 days and a million searches to find an example to follow but now I am at my wits 
end ! been about 15 years since I've done this. PLEASE help :) and thank you so much
The HTML is good I can add to it if needed but the problem area is the calendar portion and putting 
it all in the right place without an error or code issue.

I'm not sure how much more information i can provide. Like I said I am still trying to remember all 
of this stuff and trying to teach myself again and im not having much luck but i am a fast learner 
and 
can pickup by seeing how the code is written usually

Here is my code: or at least the PHP portion of it. I hope this helps.

<?php
/*MAKES THE CONNECTION*/
include 'config.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
// CHECK CONNECTION
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
/*DRAWS CALENDAR*//
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>';

$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();
$start_day = 

$calendar.= '<tr class="calendar-row">';

for($x = 0; $x < $running_day; $x++):
    $calendar.= '<td class="calendar-day-np"> </td>';
    $days_in_this_week++;
endfor;

for($list_day = 1; $list_day <= $days_in_month; $list_day++):
    $calendar.= '<td class="calendar-day">';
        /* add in the day number */
        $calendar.= '<div class="day-number">'.$list_day.'</div>';

        /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! **/
        $sql = "SELECT * FROM $tablename WHERE $current_epoch BETWEEN $start_day AND $end_day";
        /** NEED TOQUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! 
**/
$calendar.= str_repeat('<p>'.$start_day.'</p>',2);

     $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;

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>';

return $calendar;
}
$sql = "SELECT id, name, phone, item, start_day, end_day, start_time, end_time FROM $tablename";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $calendar. "id: " . $row["id"]. " - Name: " . $row["name"]. " - Phone: " . $row["phone"]. " - 
Item: " . $row["item"]. " - Start Day: " . $row["start_day"]. " - End Day:  " . $row["end_day"]. " - 
Start Time:  " . $row["start_time"]. " - End Time:  " . $row["end_time"]. "<br>";
}
} else {
echo "0 results";
}

	
	/*END OF SHOWINGCALENDAR_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
*/	
	
	
$sql = "SELECT id, name, phone, item, start_day, end_day, start_time, end_time FROM $tablename";
$result = $conn->query($sql);
	
/*GETS THE RESULTS OF THE CALENDAR FROM DATABASE TABLE*/
if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo $calendar. "id: " . $row["id"]. " - Name: " . $row["name"]. " - Phone: " . $row["phone"]. " - Item: " . $row["item"]. " - Start Day: " . $row["start_day"]. " - End Day:  " . $row["end_day"]. " - Start Time:  " . $row["start_time"]. " - End Time:  " . $row["end_time"]. "<br>";
  }
} else {
  echo "0 results";
}

 

Edited by Isfun42ofus
Link to comment
https://forums.phpfreaks.com/topic/312017-help-with-php-calendar-please/
Share on other sites

        /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! **/
        $sql = "SELECT * FROM $tablename WHERE $current_epoch BETWEEN $start_day AND $end_day";
        /** NEED TOQUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! 

If you have code outside the function that is capable of querying the database then it should be a fairly simple matter of moving that code into the function.

Note that running the query requires having the $conn variable, so you'll need to pass that into the function as another argument to be able to use it.
It also requires those two variables in there, which currently aren't being set.

Your table with events has a start and end date. How are you wanting the data displayed in the calendar - only an entry on the start date? Also, can there be multiple events on the same date? The answer to those questions will probably dictate how I would do it. I think the easiest approach would be to query all the events for the given month at the beginning of the function and put them into an array. Then when outputting the TD for any given day, check if there are any events for the day - if so, include them in the output.

I thought your code was hard to read/work with, so I modified it quite a bit

<?php
/*MAKES THE CONNECTION*/
include 'config.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
// CHECK CONNECTION
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }

/*DRAWS CALENDAR*/
function draw_calendar($month, $year, $conn)
{
    //Create timestamp for the 1st of the month
    $firstDayTimestamp = mktime(0,0,0,$month,1,$year);
    //Offset the starting date number to add empty days before the 1st of month
    $dayNo = -1 * date('w', $firstDayTimestamp) +1;
    $daysInMonth = date('t', $firstDayTimestamp);

    //Get the events for the current month
    $sql = "SELECT DAY(start_day) as day, id, name, phone, item, start_day, end_day, start_time, end_time
            FROM $tablename
            WHERE YEAR(start_day) = $year
              AND MONTH(start_day) = $month";
    $result = $conn->query($sql);
    //Put results into an array
    $events = array();
    if ($result->num_rows > 0)
    {
        // output data of each row
        while($row = $result->fetch_assoc())
        {
            $events[$row["day"]][] = $row;
        }
    }
    
    //Start the calendar table
    $calendar = '<table cellpadding="0" cellspacing="0" class="calendar" border="1">';
    //Create the calendar headings
    $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    $calendar.= "<tr class=\"calendar-row\">\n";
    foreach($headings as $heading)
    {
        $calendar.= "\t<td class=\"calendar-day-head\">{$heading}</td>\n";
    }
    $calendar.= "</tr>\n\n";

    //Create each week in the calendar
    while($dayNo <= $daysInMonth)
    {
        $calendar.= "<tr class=\"calendar-row\">\n";
        //Create each date for the week
        for($dow=0; $dow<7; $dow++)
        {
            //Check if the $dayNo is within the selected month
            if($dayNo<1 or $dayNo>$daysInMonth)
            {
                $calendar .= "\t<td class=\"calendar-day-np\"> </td>\n";
            }
            else
            {
                //Code to create content for the given day
                $calendar .= "\t<td class=\"calendar-day\">";
                $calendar .= "{$dayNo}";
                //Add any events here
                if(isset($events[$dayNo]))
                {
                    //Create outpout for each event on the current day
                    foreach($events[$dayNo] as $eventAry)
                    {
                        $calendar .= "<div>{$eventAry['name']}</div>";
                    }
               }
                $calendar .= "</td>\n";
            }
            //Increment the date
            $dayNo++;
        }
        $calendar.= "</tr>\n";
    }
    //Close the calendar table
    $calendar.= '</table>';
    return $calendar;
}

?>
<html>
<body>
<?php echo draw_calendar(1, 2021, $conn); ?>
</body>
</html>

 

8 hours ago, Isfun42ofus said:

I've been at this 3 days and a million searches to find an example to follow but now I am at my wits end !

You should have searched these forums for "calendar"...

 

Edited by Barand
<table border="1" cellpadding="5" width="800">
	<tr>
		<td valign="top">
		<form action="book.php" method="post">
			<h3>Make booking</h3>
			<p>
			<input checked="checked" name="item" type="radio" value="Meeting room" />Meeting room 
			<input name="item" type="radio" value="Swimming pool" />Swimming pool 
			<input name="item" type="radio" value="Drill" />Drill  
		  <input name="item" type="radio" value="Tennis court" />Tennis court</p>
			<table style="width: 70%">
				<tr>
					<td>Name:</td>
					<td> <input maxlength="50" name="name" type="text" required/></td>
					<td>&nbsp;</td>
					<td>&nbsp;</td>
				</tr>
				<tr>
					<td>Phone:</td>
					<td>
			<input maxlength="20" name="phone" type="text" required/></td>
					<td>&nbsp;</td>
					<td>&nbsp;</td>
				</tr>
				<tr>
					<td>Reservation time:</td>
					<td>
			<input id="from" name="start_day" type="text" required/></td>
					<td>-</td>
					<td><input id="to" name="end_day" type="text" required/></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td> <select name="start_hour">
			<option selected="selected">00</option>
			<option>01</option>
			<option>02</option>
			<option>03</option>
			<option>04</option>
			<option>05</option>
			<option>06</option>
			<option>07</option>
			<option>08</option>
			<option>09</option>
			<option>10</option>
			<option>11</option>
			<option>12</option>
			<option>13</option>
			<option>14</option>
			<option>15</option>
			<option>16</option>
			<option>17</option>
			<option>18</option>
			<option>19</option>
			<option>20</option>
			<option>21</option>
			<option>22</option>
			<option>23</option>
			</select>:<select name="start_minute">
			<option selected="selected">00</option>
			<option>30</option>
			</select></td>
					<td>&nbsp;</td>
					<td><select name="end_hour">
			<option>00</option>
			<option>01</option>
			<option>02</option>
			<option>03</option>
			<option>04</option>
			<option>05</option>
			<option>06</option>
			<option>07</option>
			<option>08</option>
			<option>09</option>
			<option>10</option>
			<option>11</option>
			<option>12</option>
			<option>13</option>
			<option>14</option>
			<option>15</option>
			<option>16</option>
			<option>17</option>
			<option>18</option>
			<option>19</option>
			<option>20</option>
			<option>21</option>
			<option>22</option>
			<option selected="selected">23</option>
			</select>:<select name="end_minute">
			<option>00</option>
			<option selected="selected">30</option>
			</select></td>
				</tr>
			</table>
			<p>
			<img id="captchaimg" src="captcha_code_file.php?rand=458910359" alt="captcha" /><br />
		  <input id="captcha" name="captcha" required="required" type="text" /></p>
			<input name="book" type="submit" value="Book" />
		</form>
		</td>
		<td valign="top">
		<h3>Cancel booking</h3>
		<form action="cancel.php" method="post">

			ID: <input name="id" required="required" type="text" /><br />
			<p>
			<img id="captchaimg2" src="captcha_code_file2.php?rand=1543010807" alt="captcha"/><br />
		  <input id="captcha2" name="captcha2" required="required" type="text" /></p>
			<p><input name="cancel" type="submit" value="Cancel" /></p>
		</form>
		</td>
		<td valign="top">
		<h3>Delete booking</h3>
		<form action="delete.php" method="post">

			ID: <input name="id" required="required" type="text" /><br />
			<p>
			<img id="captchaimg3" src="captcha_code_file3.php?rand=310655488" alt="captcha"/><br />
		  <input id="captcha3" name="captcha3" required="required" type="text" /></p>
			<p><input name="delete" type="submit" value="Delete" /></p>
		</form>
		</td>
	</tr>
    </table>
<?php
/* draws a calendar */
function draw_calendar($month,$year){

	include 'config.php';

	// Create connection
	$conn = mysqli_connect($servername, $username, $password,  $dbname);

	// Check connection
	if (!$conn) {
    	die("Connection failed: " . mysqli_connect_error());
	}

	/* draw table */
	$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';

	/* table headings */
	$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">';
			/* add in the day number */
			$calendar.= '<div class="day-number">'.$list_day.'</div>';

			/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !! **/
			   $sql = "SELECT id, name, phone, item, start_day, end_day, start_time, end_time FROM $tablename";
	
			$calendar.= str_repeat('<p> </p>',2);
			$current_epoch = mktime(0,0,0,$month,$list_day,$year);
			
			$sql = "SELECT * FROM $tablename WHERE $current_epoch BETWEEN start_day AND end_day";
						
			$result = mysqli_query($conn, $sql);
    		
    		if (mysqli_num_rows($result) > 0) {
    			// output data of each row
    			while($row = mysqli_fetch_assoc($result)) {
					if($row["canceled"] == 1) $calendar .= "<font color=\"grey\"><s>";
    				$calendar .= "<b>" . $row["item"] . "</b><br>ID: " . $row["id"] . "<br>" . $row["name"] . "<br>" . $row["phone"] . "<br>";
    				if($current_epoch == $row["start_day"] AND $current_epoch != $row["end_day"]) {
    					$calendar .= "Booking starts: " . sprintf("%02d:%02d", $row["start_time"]/60/60, ($row["start_time"]%(60*60)/60)) . "<br><hr><br>";
    				}
    				if($current_epoch == $row["start_day"] AND $current_epoch == $row["end_day"]) {
    					$calendar .= "Booking starts: " . sprintf("%02d:%02d", $row["start_time"]/60/60, ($row["start_time"]%(60*60)/60)) . "<br>";
    				}
    				if($current_epoch == $row["end_day"]) {
    					$calendar .= "Booking ends: " . sprintf("%02d:%02d", $row["end_time"]/60/60, ($row["end_time"]%(60*60)/60)) . "<br><hr><br>";
    				}
    				if($current_epoch != $row["start_day"] AND $current_epoch != $row["end_day"]) {
	    				$calendar .= "Booking: 24h<br><hr><br>";
	    			}
					if($row["canceled"] == 1) $calendar .= "</s></font>";
    			}
			} else {
    			$calendar .= "No bookings";
			}
			
		$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 AND $days_in_this_week > 1):
		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>';
	
	mysqli_close($conn);
	
	/* all done, return result */
	return $calendar;
}

include 'config.php';

$d = new DateTime(date("Y-m-d"));
echo '<h3>' . $months[$d->format('n')-1] . ' ' . $d->format('Y') . '</h3>';
echo draw_calendar($d->format('m'),$d->format('Y'));

$d->modify( 'first day of next month' );
echo '<h3>' . $months[$d->format('n')-1] . ' ' . $d->format('Y') . '</h3>';
echo draw_calendar($d->format('m'),$d->format('Y'));

$d->modify( 'first day of next month' );
echo '<h3>' . $months[$d->format('n')-1] . ' ' . $d->format('Y') . '</h3>';
echo draw_calendar($d->format('m'),$d->format('Y'));

?>

Psycho thank you but i am struggling here. I kept my original code but have added to it and it works the way its supposed to with the exception of its not seeing DB entry and returns "NO BOOKINGS"  even though there is one in there ??? Could someone just review code and see if maybe I am just retarded ? I have included complete code now including HTML.

 This is whats in my DB table

 

id   name              phone          item        start_day    end_day    start_time end_time canceled

 1name here  **********  Meeting room 1611360000 1611964800   0         84600            0

 2name here  **********Meeting room161196480      01612137600 5400   84600           0

55 minutes ago, Isfun42ofus said:

Thank You. $tablename is defined in my config.php file

You need to read up on "variable scope". Variables inside a function are local to that function. If you want to use a variable from outside the function you need to pass it as an argument to the function (along with month and year).

You need also to check queries for errors. The easiest way to do that is to put this line just before you make your connection to the database...

mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

(edit) .... and turn php's error reporting on.

Edited by Barand

Well i was able to get the info into the calendar but now it shows it on everyday on the calendar and not just the date for the booking ? I know its something stupid but like i mentioned its been to long for me to remember alot of this stuff....so its confusing . BTW, thank you ! heres a link to live page https://www.bookingisbetter.com/calendar/index.php

Edited by Isfun42ofus

If you stored your dates as something readable (like DATETIME) instead of using the unintelligible unix timestamps you would see that both those should appear on multiple days

2021-01-23 00:00:00 - 2021-01-30 00:00:00
2021-01-30 00:00:00 - 2021-02-01 00:00:00

Query each separate date is really inefficient. Get all for the month and store in an array. Then as you loop through the days, see if there are any events in the aray for that day and output them.

can someone please tell me what im doing worng ????? My calendar shows everything where its supposed to be but i must be missing something ??? config.php included and the info is in the DB. Something stupid in the code i presume. Thank you for any help......



<?php
/* draws a calendar */
function draw_calendar($month,$year){

	include 'config.php';

	// Create connection
	$conn = mysqli_connect($servername, $username, $password,  $dbname);

	// Check connection
	if (!$conn) {
    	die("Connection failed: " . mysqli_connect_error());
	}

	/* draw table */
	$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';

	/* table headings */
	$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">';
			/* add in the day number */
			$calendar.= '<div class="day-number">'.$list_day.'</div>';
	
			/**QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !!  IF MATCHES FOUND, PRINT THEM !!**/
	        $sql = 'SELECT * FROM events WHERE $current_epoch BETWEEN start_day AND end_day ORDER BY start_day, start_time';
			$result = $conn->query($sql);
			
    		if ($result->num_rows > 0) {
    			// output data of each row
    			while($row = $result->fetch_assoc()); {
						if($row["canceled"] == 1) $calendar .= "<font color=\"red\"><s>";{
						$calendar .= "<b>" . $row["item"] . "</b><br>ID: " . $row["id"] . "<br>" . $row["name"] . "<br>" . $row["phone"] . "<br>";
						}
						if($current_epoch == $row["start_day"] AND $current_epoch != $row["end_day"]) {
							$calendar .= "Booking starts: " .sprintf("%02d:%02d", $row["start_time"]/60/60, ($row["start_time"]%(60*60)/60)) . "<br><hr><br>";
						}
						if($current_epoch == $row["start_day"] AND $current_epoch = $row["end_day"]) {
							$calendar .= "Booking starts: " .sprintf("%02d:%02d", $row["start_time"]/60/60, ($row["start_time"]%(60*60)/60)) . "<br><hr>//<br>";
						}
						if($current_epoch == $row["end_day"]) {
							$calendar .= "Booking ends: " .sprintf("%02d:%02d", $row["end_time"]/60/60, ($row["end_time"]%(60*60)/60)) . "<br><hr><br>";
						}
						if($current_epoch = $row["start_day"] AND $current_epoch = $row["end_day"]) {
							$calendar .= "Booking: 24h<br><hr><br>";
						}
						if($row["canceled"] == 1){
						$calendar .= "</s></font>";
						}
				
				}
					
							
				} else {
						   $calendar .= "No bookings";
				}
		$calendar.= str_repeat('<p> </p>',2);
		$current_epoch = mktime(0,0,0,$month,$list_day,$year);
		$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 AND $days_in_this_week > 1):
		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>';
	
	mysqli_close($conn);
	
	/* all done, return result */
	return $calendar;
}

include 'config.php';

$d = new DateTime(date("Y-m-d"));
echo '<h3>' . $month[$d->format('n')-1] . ' ' . $d->format('Y') . '</h3>';
echo draw_calendar($d->format('m'),$d->format('Y'));

$d->modify( 'first day of next month' );
echo '<h3>' . $month[$d->format('n')-1] . ' ' . $d->format('Y') . '</h3>';
echo draw_calendar($d->format('m'),$d->format('Y'));

$d->modify( 'first day of next month' );
echo '<h3>' . $month[$d->format('n')-1] . ' ' . $d->format('Y') . '</h3>';
echo draw_calendar($d->format('m'),$d->format('Y'));

?>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.