Solved

PHP Calendar Not Working

Posted on 2013-10-22
10
420 Views
Last Modified: 2013-10-23
The following calendar script is not working on the "Month"  One line when I var_dump I get returns that do not include the month.

<?
//This is your Db connect file.  You need this for access	
require('htdocs/db_connect.php');
//Here are the months
$monthNames = Array("January", "February", "March", "April", "May", "June", "July", 
"August", "September", "October", "November", "December");
?>
<?php
if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("m");
if (!isset($_REQUEST["year"])) $_REQUEST["year"] = date("Y");
?>
<?php
$cMonth = $_REQUEST["month"];
$cYear = $_REQUEST["year"];
$prev_year = $cYear;
$next_year = $cYear;
$prev_month = $cMonth-1;
$next_month = $cMonth+1;
if ($prev_month == 0 ) {
	$prev_month = 12;
	$prev_year = $cYear - 1;
}
if ($next_month == 13 ) {
	$next_month = 1;
	$next_year = $cYear + 1;
}
$link_date="month=". $cMonth . "&year=" . $cYear."&";

$timestamp = mktime(0,0,0,$cMonth,1,$cYear);
$maxday = date("t",$timestamp);
$thismonth = getdate ($timestamp);
$startday = $thismonth['wday'];
for ($i=0; $i<($maxday+$startday); $i++) {
   
    if(($i % 7) == 0 ) {
        echo "<tr>\n";
    }
    if($i < $startday) {echo "<td class='calendarTd'><div id='dayNum'></div></td>\n";}
   
    else {
       
        echo "<td class='calendarTd'><div id='dayNum'>". ($i - $startday + 1)."</div>";
        $number=($i - $startday + 1);
        if ($cMonth<10){$padMonth="0".$cMonth;}
        elseif ($cMonth>10){$padMonth=$cMonth;}
        if ($number<10){$padnumber="0".$number;}
        elseif ($number>10){$padnumber=$number;}
        $full_date = $cYear."-".$padMonth."-".$padnumber;
		
		echo '<pre>';
		[b]var_dump ($full_date);[/b]

//  HERE I get returns like this: 
string(8) "2013--01"
string(8) "2013--02"	
string(8) "2013--03"
string(8) "2013--04"
AND so on.  It is not including the 10
ie:string(8) "2013-10-01"
string(8) "2013-10-02"
string(8) "2013-10-03"
	
		
		
		$next_number=$number+1;
        $next_date=$cYear."-".$cMonth."-".$next_number;
        echo "<div id ='dateInfo' style='font-size:11px;'>";
        $full_date=mysql_real_escape_string($full_date);//Use this if you are getting the date from somewhere shady.
        $q=$mysqli->query("SELECT * FROM schedule WHERE start_date = '$full_date'");
        while($r=$q->fetch_assoc()) {
            $first_name=$r['first_name'];
            $last_name=$r['last_name'];
            //You can use the event id above to code in a link if you want to make a page to view only that event.
            //This is also where you could set an image variable to
            echo $first_name." ".$last_name."<br />";
        }  
        echo "</div>";
        echo "</td>\n";
    }
    if(($i % 7) == 6 ) echo "</tr>\n";
}
?>

Open in new window

0
Comment
Question by:rgranlund
  • 5
  • 5
10 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39592096
Where in the world did you get this script?  Make a mental note to NEVER go back to that resource.

This article teaches how to handle DATETIME information in PHP.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

If you can tell us in plain, non-technical, language what you want the script to do, I can show you how to write the PHP to get the results you want.
0
 
LVL 7

Author Comment

by:rgranlund
ID: 39592121
I have entries in a DB table.  Each entry has a date and entry_title. I want to query the DB and display a calendar that has each entry_title in the appropriate, corresponding day.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39592140
See Practical Application #6 in the article.  You might put your data base query near line 40.  Please post the CREATE TABLE statement for your calendar entries, thanks.
0
 
LVL 7

Author Comment

by:rgranlund
ID: 39592181
CREATE TABLE IF NOT EXISTS `schedule` (
  `schedule_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `employee_id` varchar(30) NOT NULL,
  `first_name` varchar(40) NOT NULL,
  `last_name` varchar(40) NOT NULL,
  `start_date` date DEFAULT NULL,
  `end_date` date DEFAULT NULL,
  PRIMARY KEY (`schedule_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=38 ;

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39592193
Good!  With the columns defined as DATE data type, you can use the ISO-8601 format date to match in the query.  The PHP formatting string looks like 'Y-m-d' and it automatically includes leading zeros, leap year, daylight savings time, and all of that fun stuff.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 7

Author Comment

by:rgranlund
ID: 39592227
I'm not really sure how to write the Query and then include it day by day.  Can you point me to another example?
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points
ID: 39592546
Well, there are two ways you can do it.  If your start_date and end_date are indexed, you can run one query for every day.  This is not "efficient" but given the indexes, it will hardly be noticeable until your getting several hits per second.  The other way would be to make a single query of the entire table for everything that needed to be included in the calendar, and save the results in an array of rows.  Then you could match the rows with the days of the calendar as you build the calendar table.

This design is probably covered in many different ways in any beginning book on PHP.  I like the work from Welling and Thompson, and I recommend it as a good investment of time and money.
0
 
LVL 7

Author Comment

by:rgranlund
ID: 39595226
Thanks for the tips and recommendation on the book.  I will certainly add that to my Library for reading.

I'm almost there I think, however, I have a flaw in my logic and I'm not sure at all what is wrong with the following code.  it should return 1 item but does not.

$pdo = new PDO("mysql:host=localhost;.......");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$sql = "SELECT first_name, DATE_FORMAT(start_date, '%d') AS day
		FROM schedule
		WHERE DATE_FORMAT(start_date, '%Y-%m') = '2013-10'";
	// CURSOR_SCROLL ALLOWS REPOSITIONING THE CURSOR - LIKE DATA_SEEK() - BUT SADLY NOT WITH MYSQL
$pdos = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

	//  START FIRST QUERY TRY GRAB EMPLOYEE ID FROM SCHEDULE			
try {
    $pdos->execute();
	
	//fetch the query results into an array
	$events = $pdos->fetchAll();

// Loop through the results and put events in array
while ($row = $pdos->fetch(PDO::FETCH_OBJ)) {
    $events[$row['day']][] = $row['first_name'];
}
for($d = 1; $d <= 31; $d++) {
    if(isset($events[$d])) {
        echo count($events[$d])." events!<br />";
    } else {
        echo $d. "No events.<br />";
    }
}



}
	 catch(PDOException $e) {
   		echo 'ERROR: ' . $e->getMessage();
	}

Open in new window

0
 
LVL 7

Author Comment

by:rgranlund
ID: 39595314
@Ray;

Thanks for all of your help.  I was able to sort it out.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39595326
Thanks for the points.  Regarding this...
it should return 1 item but does not.
Almost every query you write should have a LIMIT clause.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

27 Experts available now in Live!

Get 1:1 Help Now