博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
php学习,一个简单的Calendar(2) 一个简单的活动页面
阅读量:6980 次
发布时间:2019-06-27

本文共 12893 字,大约阅读时间需要 42 分钟。

有了前面的基础,后面就是将页面展示出来。

预览图如下:1号和31号分别有活动,会一并显示出来

 

这里需要搞定几个问题,一个就是数据库的连接,我们用\sys\class\class.db_connect.inc.php

 
/*
* 数据库操作(数据库访问,认证等)
*/
 
class DB_Connect
{
/**
* Stores a database object
*
* @var object A database object
*/
protected $db;
 
/**
* Checks for a DB object or creates one if one isn't found
*
* @param object $dbo A database object
*/
protected function __construct($db = NULL)
{
if (is_object($db)) {
$this->db = $db;
} else {
// Constants are defined in /sys/config/db-cred.inc.php
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
try {
$this->db = new PDO($dsn, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . DB_ENCODE));
} catch (Exception $e) {
// If the DB connection fails, output the error
die ($e->getMessage());
}
}
}
}
 
?>

程序中需要引入DB_USER等的定义文件:db-cred.inc.php

/*
* Created on 2012-4-24 by xiongxuebing
*/
/*
* Create an empty array to store constants
*/
$C = array();
/*
* The database host URL
*/
$C['DB_HOST'] = 'localhost';
/*
* The database username
*/
$C['DB_USER'] = 'root';
/*
* The database password
*/
$C['DB_PASS'] = 'root';
/*
* The name of the database to work with
*/
$C['DB_NAME'] = 'php-jquery_example';
 
$C['DB_ENCODE'] = 'UTF8';
 
?>

 

需要注意的是,类似DB_HOST的常量并没有直接定义,而是通过在/sys/core/init.inc.php中进行定义:

foreach ($C as $name => $val) {
define($name, $val); }
原文件如下的示:
 
/*
* Created on 2016-6-19 by luhx
*/
 
session_start();
/*
* Generate an anti-CSRF token if one doesn't exist
*/
if (!isset($_SESSION['token'])) {
$_SESSION['token'] = sha1(uniqid(mt_rand(), TRUE));
}
 
/*
* Include the necessary configuration info
*/
include_once '../sys/config/db-cred.inc.php';
 
/*
* Define constants for configuration info
*/
foreach ($C as $name => $val) {
define($name, $val);
}
/*
* Create a PDO object
*/
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$dbo = new PDO($dsn, DB_USER, DB_PASS);
/*
* Define the auto-load function for classes
*/
function __autoload($class)
{
$filename = "../sys/class/class." . $class . ".inc.php";
if (file_exists($filename)) {
include_once $filename;
}
}
 
?>

 

接下来需显示日历:index.php

/*
* Created on 2012-4-24 by xiongxuebing
*/
/*
* 包含必须的文件
*/
 
include_once '../sys/core/init.inc.php';
/*
* 载入日历
*/
$cal = new Calendar($dbo, "2010-01-01 12:00:00");
 
/**
* 初始化标题和样式文件
*/
$page_title = "Events Calendar";
$css_files = array('style.css');
include_once 'assets/common/header.inc.php';
?>
 
/*
* 包含尾页
*/
include_once 'assets/common/footer.inc.php';
?>
 
首先需要创建一个Calendar
/sys/class/class.calendar.inc.php
 
/*
* Created on 2012-4-24 by xiongxuebing
*/
 
class Calendar extends DB_Connect
{
/**
* 日历根据此日期构建
* YYYY-MM-DD HH:MM:SS
* @var string
*/
private $_useDate;
/**
* 日历显示月份
* @var int
*/
private $_m;
/**
* 年
* @var int
*/
private $_y;
/**
* 这个月有多少天
* @var int
*/
private $_daysInMonth;
/**
* 这个月从周几开始
* @var int
*/
private $_startDay;
 
public function __construct($dbo = NULL, $useDate = NULL)
{
parent::__construct($dbo);
/*
* Gather and store data relevant to the month
*/
if (isset($useDate)) {
$this->_useDate = $useDate;
} else {
$this->_useDate = date('Y-m-d H:i:s');
}
$ts = strtotime($this->_useDate);
$this->_m = date('m', $ts);
$this->_y = date('Y', $ts);
$this->_daysInMonth = cal_days_in_month(
CAL_GREGORIAN,
$this->_m,
$this->_y
);
$ts = mktime(0, 0, 0, $this->_m, 1, $this->_y);
$this->_startDay = date('w', $ts);
}
 
/**
* 生成用于显示日历和活动的HTML标记
*
* 使用储存在类属性中的数据,截入给定月份的活动数据,生成并返回完整的日历HTML标记
* @return string 日历HTML标记
*/
public function buildCalendar()
{
/**
* 确定日历显示月份并创建一个用于标识日历每列星期几的缩写数组
*/
$cal_month = date('F Y', strtotime($this->_useDate));
$cal_id = date('Y-m', strtotime($this->_useDate));
$weekdays = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
/**
* 给日历标记添加一个标题
*/
$html = "\n\t

$cal_month

";
for ($d = 0, $labels = NULL; $d < 7; ++$d) {
$labels .= "\n\t\t
  • " . $weekdays[$d] . "
  • ";
    }
    $html .= "\n\t
      " . $labels . "\n\t
    ";
     
    /*
    * Load events data
    */
    $events = $this->_createEventObj();
     
    /*
    * 生成日历HTML标记
    */
    $html .= "\n\t
      "; // 开始一个新的
      for ($i = 1, $c = 1, $t = date('j'), $m = date('m'), $y = date('Y'); $c <= $this->_daysInMonth; ++$i) {
      $event_info = NULL; // clear the variable
       
      //为该月的之前几天添加填充项
      $class = $i <= $this->_startDay ? "fill" : NULL;
       
      //如果当前处理日期是今天,则为他添加class today
      if ($c == $t && $m == $this->_m && $y == $this->_y) {
      $class = "today";
      }
      $ls = sprintf("\n\t\t
    • ", $class);
    • $le = "\n\t\t";
      if ($this->_startDay < $i && $this->_daysInMonth >= $c) {
       
       
      if (isset($events[$c])) {
       
      foreach ($events[$c] as $event) {
      $link = '' . $event->title . '';
      $event_info = "\n\t\t\t$link";
      }
      }
      $date = sprintf("\n\t\t\t%02d", $c++);
      } else {
      $date = " ";
      }
      //如果赶上星期六,就新起一行
      $wrap = $i != 0 && $i % 7 == 0 ? "\n\t\n\t
        " : NULL;
       
      //Assemble the pieces into a finished item
      $html .= $ls . $date . $event_info . $le . $wrap;
      }
       
       
      //Add filler to finish out the last week
      while ($i % 7 != 1) {
      $html .= "\n\t\t
    •  
    • ";
      ++$i;
      }
       
      //Close the final unordered list
      $html .= "\n\t\n\n";
      $admin = $this->_adminGeneralOptions();
      /**
      * 返回用于输出的HTML标记
      */
      return $html . $admin;
      }
       
      /**
      * 得到活动信息HTML
      * @param int $id 活动ID
      * @return string 用于显示活动信息的基本HTML标记
      */
      public function displayEvent($id)
      {
      /**
      * Make sure an ID was passed
      * */
      if (empty($id)) {
      return NULL;
      }
      /**
      * Make sure the ID is an integer
      **/
      $id = preg_replace('/[^0-9]/', '', $id);
      /**
      * Load the event data from the DB
      **/
      $event = $this->_loadEventById($id);
      /**
      * Generate strings for the date, start, and end time
      * */
      $ts = strtotime($event->start);
      $date = date('F d, Y', $ts);
      $start = date('g:ia', $ts);
      $end = date('g:ia', strtotime($event->end));
       
      /*
      * Load admin options if the user is logged in
      */
      $admin = $this->_adminEntryOptions($id);
      return "

      $event->title

      \n\t

      $date, $start—$end

      " .
      "\n\t

      $event->description

      $admin";
      }
       
      public function displayForm()
      {
      if (isset($_POST['event_id'])) {
      $id = (int)$_POST['event_id'];
      // Force integer type to sanitize data
      } else {
      $id = NULL;
      }
      /*
      * Instantiate the headline/submit button text
      */
      $submit = "Create new!";
      /*
      * If an ID is passed, loads the associated event
      */
      if (!empty($id)) {
      $event = $this->_loadEventById($id);
      if (!is_object($event)) {
      return NULL;
      }
      $submit = "Edit event!";
      }
       
      return <<
      $submit
       or cancel
       
       
      FORM_MARKUP;
      }
       
      public function processForm()
      {
      if ($_POST['action'] != 'event_edit') {
      return "The method processForm was accessed incorrectly";
      }
      $title = htmlentities($_POST['event_title'], ENT_QUOTES, "UTF-8");
      $desc = htmlentities($_POST['event_description'], ENT_QUOTES, "UTF-8");
      $start = htmlentities($_POST['event_start'], ENT_QUOTES, "UTF-8");
      $end = htmlentities($_POST['event_end'], ENT_QUOTES, "UTF-8");
       
      if (!$this->_validDate($start) || !$this->_validDate($end)) {
      return "Invalid date format! Use YYYY-MM-DD HH:MM:SS.";
      }
      /*
      * If no event ID passed, create a new event
      */
      if (empty($_POST['event_id'])) {
      $sql = "INSERT INTO `events` (`event_title`, `event_desc`, `event_start`, `event_end`)" .
      " VALUES (:title, :description, :start, :end)";
      } else {
      $id = (int)$_POST['event_id'];
      $sql = "UPDATE `events` SET `event_title`=:title,`event_desc`=:description,`event_start`=:start,`event_end`=:end WHERE `event_id`=$id";
      }
      try {
      $stmt = $this->db->prepare($sql);
      $stmt->bindParam(":title", $title, PDO::PARAM_STR);
      $stmt->bindParam(":description", $desc, PDO::PARAM_STR);
      $stmt->bindParam(":start", $start, PDO::PARAM_STR);
      $stmt->bindParam(":end", $end, PDO::PARAM_STR);
      $stmt->execute();
      $stmt->closeCursor();
      return $this->db->lastInsertId();
      } catch (Exception $e) {
      return $e->getMessage();
      }
      }
       
      public function confirmDelete($id)
      {
      if (empty($id)) {
      return NULL;
      }
      $id = preg_replace('/[^0-9]/', '', $id);
      /*
      * If the confirmation form was submitted and the form.
      * has a valid token, check the form submission
      */
      if (isset($_POST['confirm_delete']) && $_POST['token'] == $_SESSION['token']) {
      /*
      * If the deletion is confirmed,
      * remove the event from the database
      */
      if ($_POST['confirm_delete'] == "删除") {
      $sql = "DELETE FROM `events` WHERE `event_id`=:id LIMIT 1";
      try {
      $stmt = $this->db->prepare($sql);
      $stmt->bindParam(":id", $id, PDO::PARAM_INT);
      $stmt->execute();
      $stmt->closeCursor();
      header("Location: ./");
      return;
      } catch (Exception $e) {
      return $e->getMessage();
      }
      } /*
      * If not confirmed,
      * sends the user to the main view
      */
      else {
      header("Location: ./");
      return;
      }
      }
      /*
      * If the confirmation form hasn't been submitted, display it
      * */
      $event = $this->_loadEventById($id);
      /*
      * If no object is returned, return to the main view
      * */
      if (!is_object($event)) {
      header("Location: ./");
      }
      return <<

      确定要删除 "$event->title" 吗?

      删除后将不能恢复

       
      CONFIRM_DELETE;
      }
       
      private function _validDate($date)
      {
      $pattern = '/^(\d{4}(-\d{2}){2} (\d{2})(:\d{2}){2})$/';
      /*
      * If a match is found, return TRUE. FALSE otherwise.
      */
      return preg_match($pattern, $date) == 1 ? TRUE : FALSE;
      }
       
      private function _loadEventData($id = NULL)
      {
      $sql = "SELECT `event_id`, `event_title`, `event_desc`,`event_start`, `event_end` FROM `events`";
      if (!empty($id)) {
      $sql .= "WHERE `event_id`=:id LIMIT 1";
      } else {
      $start_ts = mktime(0, 0, 0, $this->_m, 1, $this->_y);
      $end_ts = mktime(23, 59, 59, $this->_m + 1, 0, $this->_y);
      $start_date = date('Y-m-d H:i:s', $start_ts);
      $end_date = date('Y-m-d H:i:s', $end_ts);
       
      $sql .= "WHERE `event_start` BETWEEN '$start_date' AND '$end_date' ORDER BY `event_start`";
      }
      try {
      $stmt = $this->db->prepare($sql);
      /*
      * Bind the parameter if an ID was passed
      */
      if (!empty($id)) {
      $stmt->bindParam(":id", $id, PDO::PARAM_INT);
      }
      $stmt->execute();
      $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
      $stmt->closeCursor();
      return $results;
      } catch (Exception $e) {
      die ($e->getMessage());
      }
      }
       
      /**
      * 载入该月全部活动信息到一个数组
      * @return array 活动信息
      */
      private function _createEventObj()
      {
      /*
      * Load the events array
      */
      $arr = $this->_loadEventData();
      /**
      * Create a new array, then organize the events* by the day of the monthon which they occur
      * */
      $events = array();
      foreach ($arr as $event) {
      $day = date('j', strtotime($event['event_start']));
      try {
      $events[$day][] = new Event($event);
      } catch (Exception $e) {
      die ($e->getMessage());
      }
      }
      return $events;
      }
       
      private function _loadEventById($id)
      {
      /**
      * 如果id为空,返回NULL
      */
      if (empty($id)) {
      return NULL;
      }
      /**
      * 载入活动信息数组
      */
      $event = $this->_loadEventData($id);
      /**
      * 返回event对象
      */
      if (isset($event[0])) {
      return new Event($event[0]);
      } else {
      return NULL;
      }
      }
       
      private function _adminGeneralOptions()
      {
      if (isset($_SESSION['user'])) {
      return <<
      + 新 建 活 动
       
       
      ADMIN_OPTIONS;
      } else {
      return <<
      登  录
      ADMIN_OPTIONS;
      }
      }
       
      private function _adminEntryOptions($id)
      {
      if (isset($_SESSION['user'])) {
      return <<

       

       
       
      ADMIN_OPTIONS;
      } else {
      return NULL;
      }
      }
       
       
      }
       
      ?>
       

       

      然后在目录/public/assets/common/中 加入页头文件header.inc.php

       
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
       
       
       
      <?php echo $page_title; ?>
       
      href="assets/css/
      " />
       
       
       

      页尾文件footer.inc.php

       
       

       

      加入css文件:public/assets/css/style.css

      body{
      background-color:#789;
      font-famly:georgia,serif;
      font-size:13px;
      }
       
      #content {
      display:block;
      width:812px;
      margin:40px auto 10px;
      padding:10px;
      background-color:#FFF;
      -moz-border-radius:6px;
      -webkit-border-radius:6px;
      border-radius:6px;
      border:2px solid black;
      -moz-box-shadow:0 0 14px #123;
      -webkit-box-shadow:0 0 14px #123;
      box-shadow:0 0 14px #123;
      }
       
      h2,p{
      margin:0 auto 14px;
      text-align:center;
      }
       
      ul{
      display:block;
      clear:left;
      height:82px;
      width:812px;
      margin:0 auto;
      padding: 0;
      list-style:none;
      background-color:#FFF;
      text-align:center;
      border:1px solid black;
      border-top: 0;
      border-bottom: 2px solid black;
      }
       
      li {
      position:relative;
      float:left;
      margin:0;
      padding:20px 2px 2px;
      border-left:1px solid black;
      border-right:1px solid black;
      width: 110px;
      height: 60px;
      overflow:hidden;
      background-color:white;
      }
       
      li:hover{
      background-color:#FCB;
      z-index:1;
      -moz-box-shadow: 0 0 10px #789;
      -webkit-box-shadow: 0 0 10px #789;
      box-shadow:0 0 10px #789;
      }
       
      .weekdays{
      height: 20px;
      border-top: 2px solid black;
      }
      .weekdays li{
      height: 16px;
      padding: 2px 2px;
      background-color: #BCF;
      }
       
      .fill{
      background-color:#BCD;
      }
       
      .weekdays li:hover,li.fill:hover{
      background-color:#BCD;
      -moz-box-shadow: none;
      -webkit-box-shadow: none;
      box-shadow: none;
      }
       
      .weekdays li:hover,.today{
      background-color: #BCF;
      }
       
      li strong {
      position:absolute;
      top: 2px;
      right:2px;
      }
       
      li a {
      position: relative;
      display:block;
      border: 1px dotted black;
      margin:2px;
      padding:2px;
      font-size:11px;
      background-color:#BEF;
      text-align:left;
      -moz-border-radius: 6px;
      -webkit-border-radius:6px;
      border-radius:6px;
      z-index:1;
      text-decoration:none;
      color:black;
      font-weight:bold;
      font-style:italic;
      }
       
      li a:hover {
      background-color:#BCF;
      z-index:2;
      -moz-box-shadow: 0 0 6px #789;
      -webkit-box-shadow: 0 0 6px #789;
      box-shadow: 0 0 6px #789;
      }
       

      本篇文章对应代码:

      转载地址:http://bvjpl.baihongyu.com/

      你可能感兴趣的文章
      HDU 1052 - Tian Ji -- The Horse Racing
      查看>>
      【NOIP】提高组2012 同余方程
      查看>>
      RvmTranslator7.1
      查看>>
      ReentrantLock与synchronized
      查看>>
      TCP
      查看>>
      爬虫基本原理
      查看>>
      2_1_6 递归与分治策略(汉诺塔问题)
      查看>>
      AtCoder Regular Contest 082
      查看>>
      实验一
      查看>>
      javascript核心
      查看>>
      CSS三大特性:层叠性、继承性、优先级
      查看>>
      组件的创建方式1
      查看>>
      Net基础复习
      查看>>
      自怨自艾和怨天尤人
      查看>>
      uva 515 King
      查看>>
      Quartz实现定时任务实例
      查看>>
      python爬虫的scrapy安装+pymongo的安装
      查看>>
      webservice gsoap 小记
      查看>>
      TesCase-GUI(图形用户界面)测试
      查看>>
      自问自答 学习系列(1):从图像分类,到损失函数,到神经网络
      查看>>