Prosty Kalendarz (PHP, MySQL)
Struktura tabeli w bazie danych:
CREATE TABLE IF NOT EXISTS `kalendarz` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(65) NOT NULL,
`desc` varchar(255) NOT NULL,
`date` varchar(11) NOT NULL,
`stamp` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf-8 AUTO_INCREMENT=0;
Postaramy się utworzyć prosty funkcjonalny kalendarz, który wywoła formularz i wstawi wydarzenia do bazy danych w połączeniu z JS.
<script>
//przejście do poprzedniego miesiąca
function goLastMonth(month, year){
// If the month is January, decrement the year
if(month == 1){
--year;
month = 13;
}
document.location.href = '<?=$_SERVER['PHP_SELF'];?>?month='+(month-1)+'&year='+year;
}
// przejście do następnego miesiąca
//next function
function goNextMonth(month, year){
// If the month is December, increment the year
if(month == 12){
++year;
month = 0;
}
document.location.href = '<?=$_SERVER['PHP_SELF'];?>?month='+(month+1)+'&year='+year;
}
//Funkcja ograniczająca ilość znaków w opisie wydarzenia
function remChars(txtControl, txtCount, intMaxLength)
{
if(txtControl.value.length > intMaxLength)
txtControl.value = txtControl.value.substring(0, (intMaxLength-1));
else
txtCount.value = intMaxLength - txtControl.value.length;
}
// Funkcja sprawdzająca, czy wszystkie pola formularza są wypełnione, zanim wyświetli przycisk submit użytkownikowi
function checkFilled() {
var filled = 0
var x = document.form1.name.value;
//x = x.replace(/^\s+/,""); // usunięcie spacji początkowych
if (x.length > 0) {filled ++}
var y = document.form1.desc.value;
//y = y.replace(/^s+/,""); // usunięcie spacji początkowych
if (y.length > 0) {filled ++}
if (filled == 2) {
document.getElementById("Submit").disabled = false;
}
else {document.getElementById("Submit").disabled = true} // w przypadku, gdy pole jest wypełnione, a następnie usunięte
}
</script>
Teraz przejdźmy do skryptów php:
// Pobierz wartości z kwerendy
$day = (isset($_GET["day"])) ? $_GET['day'] : "";
$month = (isset($_GET["month"])) ? $_GET['month'] : "";
$year = (isset($_GET["year"])) ? $_GET['year'] : "";
Używa się powyższych zmiennych trójskładnikowych (operatorów warunkowych), aby sprawdzić, czy coś jest prawdziwe czy fałszywe:
i.e. $day = (isset($_GET["day"])) ? $_GET['day'] : "";
(isset($_GET["day"])) warunek ten jest pytaniem, czy jest ustawiony
Znak ? dzieli wyrażenie na dwa etapy
$_GET['day'] wartość ta będzie obowiązywać, jeżeli powyższy warunek jest spełniony
Znak : oddziela prawdę od fałszywej wartości.
"" deklaruje, że zmienna jest pusta, jeśli nie jest stworzona przez kwendę $ _GET.
function hiLightEvt($eMonth,$eDay,$eYear){
//$tDayName = date("l");
$todaysDate = date("n/j/Y");
$dateToCompare = $eMonth . '/' . $eDay . '/' . $eYear;
if($todaysDate == $dateToCompare){
//$aClass = '<span>' . $tDayName . '</span>';
$aClass='class="today"';
}else{
//$dateToCompare = $eMonth . '/' . $eDay . '/' . $eYear;
//echo $todaysDate;
//return;
$sql="select count(date) as eCount from kalendarz where date = '" . $eMonth . '/' . $eDay . '/' . $eYear . "'";
//echo $sql;
//return;
$result = mysql_query($sql);
while($row= mysql_fetch_array($result)){
if($row['eCount'] >=1){
$aClass = 'class="event"';
}elseif($row['eCount'] ==0){
$aClass ='class="normal"';
}
}
}
return $aClass;
Powyższa funkcja pobiera wydarzenia z naszej bazy danych i dopasowuje ją do dnia, w którym faktycznie ma wydarzenie. Kiedy to robi dla tego dnia, zdarzenie zostanie wydrukowane na ekranie i komórka zostanie podświetlona.
To jest nasz kod kalendarza html w PHP i odwołuje się do funkcji JS (utworzonych wcześniej)
<table width="350" cellpadding="0" cellspacing="0">
<tr>
<td width="50" colspan="1">
<input type="button" value=" < " onClick="goLastMonth(<?php echo $month . ", " . $year; ?>);">
</td>
<td width="250" colspan="5">
<span class="title"><?php echo $monthName . " " . $year; ?></span><br>
</td>
<td width="50" colspan="1" align="right">
<input type="button" value=" > " onClick="goNextMonth(<?php echo $month . ", " . $year; ?>);">
</td>
</tr>
<tr>
<th>Ni</td>
<th>Po</td>
<th>Wt</td>
<th>Śr</td>
<th>Cz</td>
<th>Pi</td>
<th>So</td>
</tr>
<tr>
<?php
for($i = 1; $i < $numDays+1; $i++, $counter++){
$dateToCompare = $month . '/' . $i . '/' . $year;
$timeStamp = strtotime("$year-$month-$i");
//echo $timeStamp . '<br/>';
if($i == 1){
// Workout when the first day of the month is
$firstDay = date("w", $timeStamp);
for($j = 0; $j < $firstDay; $j++, $counter++){
echo "<td> </td>";
}
}
if($counter % 7 == 0){
?>
</tr><tr>
<?php
}
?>
<!--right here--><td width="50" <?=hiLightEvt($month,$i,$year);?>><a href="<?=$_SERVER['PHP_SELF'] . '?month='. $month . '&day=' . $i . '&year=' . $year;?>&v=1"><?=$i;?></a></td>
<?php
}
?>
</table>
Wskazówka:
onClick="goNextMonth(<?php echo $month . ", " . $year; ?>);
<?php
if(isset($_GET['v'])){
if(isset($_POST['Submit'])){
$sql="insert into kalendarz(name,desc,date,stamp) values('" . $_POST['name'] ."','" . $_POST['desc'] . "','" . $_POST['date'] . "',now())";
mysql_query($sql);
}
$sql="select name,desc, DATE_FORMAT(stamp, '%a %b %e %Y') as stamp from kalendarz where date = '" . $month . '/' . $day . '/' . $year . "'";
//echo $sql;
//return;
$result = mysql_query($sql);
$numRows = mysql_num_rows($result);
?>
Oto ostatnia strony:
$sql="select name,desc, DATE_FORMAT(stamp, '%a %b %e %Y') as stamp from kalendarz where date = '" . $month . '/' . $day . '/' . $year . "'";
//echo $sql;
//return;
$result = mysql_query($sql);
$numRows = mysql_num_rows($result);
?>
<a href="<?=$_SERVER['PHP_SELF'];?>?month=<?=$_GET['month'] . '&day=' . $_GET['day'] . '&year=' . $_GET['year'];?>&v=1&f=true">New Event</a><br/>
<?php
if(isset($_GET['f'])){
include 'form.php';
}
if($numRows == 0 ){
echo '<h3>No Events</h3>';
}else{
//echo '<ul>';
echo '<h3>Events Listed</h3>';
while($row = mysql_fetch_array($result)){
?>
<div class="output">
<h5><?=$row['name'];?></h5>
<?=$row['desc'];?><br/>
Listed On: <?=$row['stamp'];?>
</div>
<?php
}
}
}
?>
Oto kod w całości:
<?php
//database settings
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function goLastMonth(month, year){
// If the month is January, decrement the year
if(month == 1){
--year;
month = 13;
}
document.location.href = '<?=$_SERVER['PHP_SELF'];?>?month='+(month-1)+'&year='+year;
}
//next function
function goNextMonth(month, year){
// If the month is December, increment the year
if(month == 12){
++year;
month = 0;
}
document.location.href = '<?=$_SERVER['PHP_SELF'];?>?month='+(month+1)+'&year='+year;
}
function remChars(txtControl, txtCount, intMaxLength)
{
if(txtControl.value.length > intMaxLength)
txtControl.value = txtControl.value.substring(0, (intMaxLength-1));
else
txtCount.value = intMaxLength - txtControl.value.length;
}
function checkFilled() {
var filled = 0
var x = document.form1.name.value;
//x = x.replace(/^\s+/,""); // strip leading spaces
if (x.length > 0) {filled ++}
var y = document.form1.desc.value;
//y = y.replace(/^s+/,""); // strip leading spaces
if (y.length > 0) {filled ++}
if (filled == 2) {
document.getElementById("Submit").disabled = false;
}
else {document.getElementById("Submit").disabled = true} // in case a field is filled then erased
}
</script>
<style>
body{
font-family:Georgia, "Times New Roman", Times, serif;
font-size:12px;
}
.today{
background-color:#00CCCC;
font-weight:bold;
background-repeat:no-repeat;
background-position:center;
position:relative;
}
.today span{
position:absolute;
left:0;
top:0;
}
.today a{
color:#000000;
padding-top:10px;
}
.selected {
color: #FFFFFF;
background-color: #C00000;
}
.event {
background-color: #C6D1DC;
border:1px solid #ffffff;
}
.normal {
}
table{
border:1px solid #cccccc;
padding:3px;
}
th{
width:36px;
background-color:#cccccc;
text-align:center;
color:#ffffff;
border-left:1px solid #ffffff;
}
td{
text-align:center;
padding:10px;
margin:0;
}
table.tableClass{
width:350px;
border:none;
border-collapse: collapse;
font-size:85%;
border:1px dotted #cccccc;
}
table.tableClass input,textarea{
font-size:90%;
}
#form1{
margin:5px 0 0 0;
}
#greyBox{
height:10px;
width:10px;
background-color:#C6D1DC;
border:1px solid #666666;
margin:5px;
}
#legend{
margin:5 0 10px 50px;
width:200px;
}
#hr{border-bottom:1px solid #cccccc;width:300px;}
.output{width:300px;border-bottom:1px dotted #ccc;margin-bottom:5px;padding:6px;}
h5{margin:0;}
</style>
</head>
<body>
<?php
setlocale(LC_ALL, 'pl_PL', 'pl_PL', 'pl', 'polish');
function data_po_polsku($string)
{
$string = str_replace('Mon', 'poniedziałek', $string);
$string = str_replace('Tue', 'wtorek', $string);
$string = str_replace('Wed', 'środa', $string);
$string = str_replace('Thu', 'czwartek', $string);
$string = str_replace('Fri', 'piątek', $string);
$string = str_replace('Sat', 'sobota', $string);
$string = str_replace('Sun', 'niedziela', $string);
$string = str_replace('January', 'styczeń', $string);
$string = str_replace('February', 'luty', $string);
$string = str_replace('March', 'marzec', $string);
$string = str_replace('April', 'kwiecień', $string);
$string = str_replace('May', 'maj', $string);
$string = str_replace('June', 'czerwiec', $string);
$string = str_replace('July', 'lipiec', $string);
$string = str_replace('August', 'sierpień', $string);
$string = str_replace('September', 'wrzesień', $string);
$string = str_replace('October', 'październik', $string);
$string = str_replace('November', 'listopad', $string);
$string = str_replace('December', 'grudzień', $string);
return $string;
}
//$todaysDate = date("n/j/Y");
//echo $todaysDate;
// Get values from query string
$day = (isset($_GET["day"])) ? $_GET['day'] : "";
$month = (isset($_GET["month"])) ? $_GET['month'] : "";
$year = (isset($_GET["year"])) ? $_GET['year'] : "";
//comparaters for today's date
//$todaysDate = date("n/j/Y");
//$sel = (isset($_GET["sel"])) ? $_GET['sel'] : "";
//$what = (isset($_GET["what"])) ? $_GET['what'] : "";
//$day = (!isset($day)) ? $day = date("j") : $day = "";
if(empty($day)){ $day = date("j"); }
if(empty($month)){ $month = date("n"); }
if(empty($year)){ $year = date("Y"); }
//set up vars for calendar etc
$currentTimeStamp = strtotime("$year-$month-$day");
$monthName = date("F", $currentTimeStamp);
$numDays = date("t", $currentTimeStamp);
$counter = 0;
//$numEventsThisMonth = 0;
//$hasEvent = false;
//$todaysEvents = "";
//run a selec statement to hi-light the days
function hiLightEvt($eMonth,$eDay,$eYear){
//$tDayName = date("l");
$todaysDate = date("n/j/Y");
$dateToCompare = $eMonth . '/' . $eDay . '/' . $eYear;
if($todaysDate == $dateToCompare){
//$aClass = '<span>' . $tDayName . '</span>';
$aClass='class="today"';
}else{
//$dateToCompare = $eMonth . '/' . $eDay . '/' . $eYear;
//echo $todaysDate;
//return;
$sql="select count(date) as eCount from kalendarz where date = '" . $eMonth . '/' . $eDay . '/' . $eYear . "'";
//echo $sql;
//return;
$result = mysql_query($sql);
while($row= mysql_fetch_array($result)){
if($row['eCount'] >=1){
$aClass = 'class="event"';
}elseif($row['eCount'] ==0){
$aClass ='class="normal"';
}
}
}
return $aClass;
}
?>
<table width="350" cellpadding="0" cellspacing="0">
<tr>
<td width="50" colspan="1">
<input type="button" value=" < " onclick="goLastMonth(<?php echo $month . ", " . $year; ?>);">
</td>
<td width="250" colspan="5">
<span class="title"><?php echo data_po_polsku($monthName) . " " . $year; ?></span><br>
</td>
<td width="50" colspan="1" align="right">
<input type="button" value=" > " onclick="goNextMonth(<?php echo $month . ", " . $year; ?>);">
</td>
</tr>
<tr>
<th>Ni</th>
<th>Po</th>
<th>Wt</th>
<th>Śr</th>
<th>Cz</th>
<th>Pi</th>
<th>So</th>
</tr>
<tr>
<?php
for($i = 1; $i < $numDays+1; $i++, $counter++){
$dateToCompare = $month . '/' . $i . '/' . $year;
$timeStamp = strtotime("$year-$month-$i");
//echo $timeStamp . '<br/>';
if($i == 1){
// Workout when the first day of the month is
$firstDay = date("w", $timeStamp);
for($j = 0; $j < $firstDay; $j++, $counter++){
echo "<td> </td>";
}
}
if($counter % 7 == 0){
echo "</tr><tr>";
}
?>
<!--right here--><td width="50" <?=hiLightEvt($month,$i,$year);?>><a href="<?=$_SERVER['PHP_SELF'] . '?month='. $month . '&day=' . $i . '&year=' . $year;?>&v=1"><?=$i;?></a></td>
<?php
}
?>
</table>
<?php
if(isset($_GET['v'])){
if(isset($_POST['Submit'])){
$sql="insert into kalendarz(name,desc,date,stamp) values('" . $_POST['name'] ."','" . $_POST['desc'] . "','" . $_POST['date'] . "',now())";
mysql_query($sql);
}
$sql="select name,desc, DATE_FORMAT(stamp, '%a %b %e %Y') as stamp from kalendarz where date = '" . $month . '/' . $day . '/' . $year . "'";
//echo $sql;
//return;
$result = mysql_query($sql);
$numRows = mysql_num_rows($result);
?>
<a href="<?=$_SERVER['PHP_SELF'];?>?month=<?=$_GET['month'] . '&day=' . $_GET['day'] . '&year=' . $_GET['year'];?>&v=1&f=true">Dodaj wydarzenie</a><br>
<?php
if(isset($_GET['f'])){
include 'form.php';
}
if($numRows == 0 ){
echo '<h3>Brak wydarzeń</h3>';
}else{
//echo '<ul>';
echo '<h3>Lista wydarzeń</h3>';
while($row = mysql_fetch_array($result)){
?>
<div class="output">
<h5><?=$row['name'];?></h5>
<?=$row['desc'];?><br>
Dodano: <?=data_po_polsku($row['stamp']);?>
</div>
<?php
}
}
}
?>
</body>
</body>
</html>
Plik formularza form.php
<form id="form1" name="form1" method="post" action="<?=$_SERVER['PHP_SELF'].'?month=' .$_GET['month'] . '&day=' . $_GET['day'] . '&year=' . $_GET['year'];?>&v=1">
<table cellpadding="0" cellspacing="0" class="tableClass">
<tr>
<td width="142">Nazwa</td>
<td width="146"><div align="left">
<input type="text" name="name" id="name" onKeyup="checkFilled();">
</div></td>
</tr>
<tr>
<td rowspan="2">Opis</td>
<td><div align="left">
<textarea name="desc" id="desc" cols="15" rows="5" onKeyDown="remChars(this, document.form1.txtCount, 200);"
onKeyUp="remChars(this, document.form1.txtCount, 200);checkFilled();"></textarea>
<br/>
</div></td>
</tr>
<tr>
<td>Pozostało
<input readonly name="txtCount" type="text" id="txtCount" value="200" size="2" maxlength="3">
znaków!</td>
</tr>
<tr>
<td>Data Wydarzenia</td>
<td><div align="left">
<input type="text" name="date" id="date" value="<?= $_GET['day']. '/' . $_GET['month'] . '/' . $_GET['year'];?>" readonly>
</div></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="Submit" id="Submit" value="Dodaj" disabled></td>
</tr>
</table>
</form>