The third day of php practical combat_PHP tutorial

WBOY
Release: 2016-07-14 10:10:48
Original
866 people have browsed it



I made a new layout and it feels more comfortable than before.

The special effects of jquery have also been modified. Move to the content area and change the color of the text to a beautiful blue. Remove it.


[javascript] // JavaScript Document
$(document).ready(function(e) {
$user=$("div .user");
$text=$("div .text");
       
$("div .content").each(function(index){
         $(this).mousemove(function(){
                                                                  $user.eq(index).css("color","#0A8CD2");

// $user.eq(index).css("background","#FFE6AD");
// $text.eq(index).css("background","#FFFDF6");
                                                                  }).mouseout(function(){
                                                                  $user.eq(index).css("color","#000");

// $user.eq(index).css("background","#E6F0F9");
// $text.eq(index).css("background","#F8FBFD");
        });
});

       
});

// JavaScript Document
$(document).ready(function(e) {

$user=$("div .user");

$text=$("div .text");

$("div .content").each(function(index){
$(this).mousemove(function(){

$user.eq(index).css("color","#0A8CD2");

// $user.eq(index).css("background","#FFE6AD");
// $text.eq(index).css("background","#FFFDF6");

}).mouseout(function(){

$user.eq(index).css("color","#000");

// $user.eq(index).css("background","#E6F0F9");
// $text.eq(index).css("background","#F8FBFD");

});

});


});

A time field has been added to the database, with type int and length 11;

When adding a message, call the time() function to return the ux timestamp,

When reading from the database, call the date() function

[php] date('Y-m-d H:i:s',$value['time']);//Convert timestamp to date

date('Y-m-d H:i:s',$value['time']);//Convert timestamp to date
Then also added a paging code


[php] function index() {

Include "page.class.php";
                                                                    $rows = $this->db->count('select * from data');

$page = new Page($rows, 5, "");

$page -> set("head", "Message");
$page -> set("first", "Homepage")
-> set("prev", "previous page")
-> set("next", "next page")
-> set("last", "last page");

$list=$this->db
->order('id DESC')
->limit($page->getLimit())
->select();
       
$this->assign("page",$page->fpage(0,3,4,5,6));
$this->assign("list",$list);
$this->assign("title", "My Message Board"); //Assign the title variable to the header template header.tpl
       

$this->display(); //Including replacing the variables in the template and outputting the template page
}

function index() {

include "page.class.php";

       
$rows = $this->db->count('select * from data');

$page = new Page($rows, 5, "");


$page -> set("head", "Message");
$page -> set("first", "Homepage")
-> set("prev", "previous page")
-> set("next", "next page")
-> set("last", "last page");

$list=$this->db
->order('id DESC')
->limit($page->getLimit())
->select();
 
$this->assign("page",$page->fpage(0,3,4,5,6));
$this->assign("list",$list);
$this->assign("title", "My Message Board"); //Assign the title variable to the header template header.tpl
 

$this->display(); //Including replacing the variables in the template and outputting the template page
}
The effect is pretty good.

page.class.php source code is attached

[php] /**
File: page.class.php
​​​​Perfect paging type Page
@Qq496928838
​*/
Class Page {
private $total; private $listRows; Private $ Limit; // SQL statement uses limit clauses to limit the number of records
private $uri; //Automatically obtain the request address of the url
private $pageNum; private $page;         private $config = array(
'head' => "record",
'prev' => "Previous page",
'next' => "Next page",
'first'=> "Home",
'last' => "Last page"
                                        ); Private $ listnum = 10; // The number of default layout lists

/**
​​​​​​Construction method, you can set the properties of the paging class
                                                                                                  use   use   with   using                     ’ s ’ s ’ s ’ s ’ s ‐ ‐ ‐ ‐ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​                                                                                                                                                                                                                                                   ’ s ’ s ’ s ’ s ’ s ’ ’ to ’to 1-- @Param Mixed $ Query can choose parameters to the target page, which can be an array or query string format
@param bool $ord Optional, the default value is true, the page will be displayed from the first page, false will be the last page
                     */
        public function __construct($total, $listRows=25, $query="", $ord=true){
$this->total = $total;
            $this->listRows = $listRows; 
            $this->uri = $this->getUri($query); 
            $this->pageNum = ceil($this->total / $this->listRows); 
            /*以下判断用来设置当前面*/ 
            if(!empty($_GET["page"])) { 
                $page = $_GET["page"]; 
            }else{ 
                if($ord) 
                    $page = 1; 
                else 
                    $page = $this->pageNum; 
            } 
 
            if($total > 0) { 
                if(preg_match('/D/', $page) ){ 
                    $this->page = 1; 
                }else{ 
                    $this->page = $page; 
                } 
            }else{ 
                $this->page = 0; 
            } 
             
            $this->limit = "LIMIT ".$this->getLimit(); 
        } 
 
        /**
For the information for setting the paging, you can perform coherent operations
@param string $param is the subscript of the member attribute array config
@param string $value is used to set the element value corresponding to the config subscript
               @return object                                                                                                                                                                                                                                                                       out out out of the blue can be used as a reference.                      */ 
        function set($param, $value){ 
            if(array_key_exists($param, $this->config)){ 
                $this->config[$param] = $value; 
            } 
            return $this; 
        } 
         
        /* 不是直接去调用,通过该方法,可以使用在对象外部直接获取私有成员属性limit和page的值 */ 
        function __get($args){ 
            if($args == "limit" || $args == "page") 
                return $this->$args; 
            else 
                return null; 
        } 
         
        /**
            按指定的格式输出分页
            @param  int 0-7的数字分别作为参数,用于自定义输出分页结构和调整结构的顺序,默认输出全部结构
            @return string  分页信息内容
         */ 
        function fpage(){ 
            $arr = func_get_args(); 
 
            $html[0] = " 共 {$this->total} {$this->config["head"]} "; 
            $html[1] = " 本页 ".$this->disnum()." 条 "; 
            $html[2] = " 本页从 {$this->start()}-{$this->end()} 条 "; 
            $html[3] = " {$this->page}/{$this->pageNum}页 "; 
            $html[4] = $this->firstprev(); 
            $html[5] = $this->pageList(); 
            $html[6] = $this->nextlast(); 
            $html[7] = $this->goPage(); 
 
            $fpage = '

'; 
            if(count($arr) < 1)
$arr = array(0, 1,2,3,4,5,6,7);

for($i = 0; $i < count($arr); $i++)
$fpage .= $html[$arr[$i]];

$fpage .= '
';
                return $fpage;
         } 
                                   
​ ​ ​ /* The format is 1,5,*/
function getLimit(){
If($this->page > 0)
                    return ($this->page-1)*$this->listRows.", {$this->listRows}";
                                                                                    else Return 0;
         } 

              /* Private method used inside the object to automatically obtain the current URL visited */
         private function getUri($query){                                                         $request_uri = $_SERVER["REQUEST_URI"];
$url = strstr($request_uri,'?') ? $request_uri : $request_uri.'?';
                                                                 If(is_array($query))
                        $url .= http_build_query($query);
               else if($query != "")
                     $url .= "&".trim($query, "?&");
                                   
                $arr = parse_url($url);

If(isset($arr["query"])){
                    parse_str($arr["query"], $arrs);
                   unset($arrs["page"]);
$url = $arr["path"].'?'.http_build_query($arrs);
                                                                                                                                                                                                       If(strstr($url, '?')) {
If(substr($url, -1)!='?')
$url = $url.'&';
              }else{
$url = $url.'?';
                                                                                                                                                                                                                      return $url;
         } 

                 /* Private method used inside the object to get the number of records at the beginning of the current page */
        private function start(){
If($this->total == 0)
Return 0;
                                                                                    else                    return ($this->page-1) * $this->listRows+1;
         } 

              /* Private method used inside the object to get the number of records at the end of the current page */
        private function end(){
                return min($this->page * $this->listRows, $this->total);
         } 

                               /* Private method used inside the object to obtain the operation information of the previous page and home page */
         private function firstprev(){
If($this->page > 1) {
                      $str = " {$this->config["first"]} ";
$str .= "{$this->config["prev"] } "; 
                                   return $str;                                                                                                                                                             
         } 
       
               /* Private method used inside the object to obtain page list information */
         private function pageList(){
               $linkPage = " ";
                                                                                   $inum = floor($this->listNum/2);
                                                                                                   /*List in front of the current page */ 
for($i = $inum; $i >= 1; $i--){
$page = $this->page-$i;

If($page >= 1)
                                    $linkPage .= "{$page} ";
                                                                                                                                                                 /*Information of the current page */ 
If($this->pageNum > 1)
                      $linkPage .= "{$this->page} ";
                                                                                                                                                                                                                                                                                                                                                    /*List behind the current page */ 
for($i=1; $i <= $inum; $i++){
$page = $this->page+$i;
If($page <= $this->pageNum)
                                    $linkPage .= "{$page} ";
              else break;
                                                                                                                                      $linkPage .= '
';
               return $linkPage;
         } 

              /* Private method used inside the object to obtain the operation information of the next page and the last page */
private function nextlast(){
If($this->page != $this->pageNum) {
$str = " {$this->config["next"]} ";
$str .= " {$this->config["last"]}< ;/a> ";
                             return $str;                                                                                                                                                                         } 

/ * Private method used inside the object, used to display and process form jump pages * /
        private function goPage(){
If($this->pageNum > 1) {
return ' ';
                                                                                                                                               } 

/* Private method used inside the object to obtain the number of records displayed on this page */
         private function disnum(){
If($this->total > 0){
Return $this->end()-$this->start()+1;
              }else{
Return 0;
                                                                                                                                               } 
}  

       
       
       

/**
file: page.class.php

Perfect paging type Page

@微 Cool QQ496928838
​*/
class Page {
private $total; //Total number of records in the data table
private $listRows; //Display number of rows per page
private $limit; //SQL statement uses limit clause to limit the number of records obtained
private $uri; //Automatically obtain the request address of the url
private $pageNum; //Total number of pages
private $page; //Current page
private $config = array(
        'head' => "record",
        'prev' => "Previous page",
'next' => "Next page",
        'first'=> "Home",
        'last' => "Last page"
);        // Display content in paging information, you can set it yourself through the set() method
private $listNum = 10; //The number of items displayed in the default paging list

  /**
   构造方法,可以设置分页类的属性
   @param int $total  计算分页的总记录数
   @param int $listRows 可选的,设置每页需要显示的记录数,默认为25条
   @param mixed $query 可选的,为向目标页面传递参数,可以是数组,也可以是查询字符串格式
   @param  bool $ord 可选的,默认值为true, 页面从第一页开始显示,false则为最后一页
   */
  public function __construct($total, $listRows=25, $query="", $ord=true){
   $this->total = $total;
   $this->listRows = $listRows;
   $this->uri = $this->getUri($query);
   $this->pageNum = ceil($this->total / $this->listRows);
   /*以下判断用来设置当前面*/
   if(!empty($_GET["page"])) {
    $page = $_GET["page"];
   }else{
    if($ord)
     $page = 1;
    else
     $page = $this->pageNum;
   }

   if($total > 0) {
    if(preg_match('/\D/', $page) ){
     $this->page = 1;
    }else{
     $this->page = $page;
    }
   }else{
    $this->page = 0;
   }
   
   $this->limit = "LIMIT ".$this->getLimit();
  }

  /**
   用于设置显示分页的信息,可以进行连贯操作
   @param string $param 是成员属性数组config的下标
   @param string $value 用于设置config下标对应的元素值
   @return object   返回本对象自己$this, 用于连惯操作
   */
  function set($param, $value){
   if(array_key_exists($param, $this->config)){
    $this->config[$param] = $value;
   }
   return $this;
  }
  
  /* 不是直接去调用,通过该方法,可以使用在对象外部直接获取私有成员属性limit和page的值 */
  function __get($args){
   if($args == "limit" || $args == "page")
    return $this->$args;
   else
    return null;
  }
  
  /**
   按指定的格式输出分页
   @param int 0-7的数字分别作为参数,用于自定义输出分页结构和调整结构的顺序,默认输出全部结构
   @return string 分页信息内容
   */
  function fpage(){
   $arr = func_get_args();

   $html[0] = " 共 {$this->total} {$this->config["head"]} ";
   $html[1] = " 本页 ".$this->disnum()." 条 ";
   $html[2] = " 本页从 {$this->start()}-{$this->end()} 条 ";
   $html[3] = " {$this->page}/{$this->pageNum}页 ";
   $html[4] = $this->firstprev();
   $html[5] = $this->pageList();
   $html[6] = $this->nextlast();
   $html[7] = $this->goPage();

   $fpage = '

';
   if(count($arr) < 1)
$arr = array(0, 1,2,3,4,5,6,7);

for($i = 0; $i < count($arr); $i++)
$fpage .= $html[$arr[$i]];

$fpage .= '
';
Return $fpage;
}

/* The format is 1,5,*/
function getLimit(){
If($this->page > 0)
Return ($this->page-1)*$this->listRows.", {$this->listRows}";
else
Return 0;
}

/* Private method used inside the object to automatically obtain the current URL visited */
private function getUri($query){
$request_uri = $_SERVER["REQUEST_URI"];
$url = strstr($request_uri,'?') ? $request_uri : $request_uri.'?';
 
If(is_array($query))
$url .= http_build_query($query);
else if($query != "")
$url .= "&".trim($query, "?&");

$arr = parse_url($url);

if(isset($arr["query"])){
Parse_str($arr["query"], $arrs);
​​unset($arrs["page"]);
$url = $arr["path"].'?'.http_build_query($arrs);
}
 
if(strstr($url, '?')) {
If(substr($url, -1)!='?')
$url = $url.'&';
}else{
$url = $url.'?';
}
 
Return $url;
}

/* Private method used inside the object to obtain the number of records at the beginning of the current page */
private function start(){
if($this->total == 0)
Return 0;
else
Return ($this->page-1) * $this->listRows+1;
}

/* Private method used inside the object to obtain the number of records at the end of the current page */
private function end(){
Return min($this->page * $this->listRows, $this->total);
}

/* Private method used inside the object to obtain operation information of the previous page and home page */
private function firstprev(){
if($this->page > 1) {
$str = "
{$this->config["first"]} ";
$str .= "{$this->config["prev"] } ";
Return $str;
}

}

/* Private method used inside the object to obtain page list information */
private function pageList(){
$linkPage = " ";
 
$inum = floor($this->listNum/2);
/*List in front of current page */
for($i = $inum; $i >= 1; $i--){
$page = $this->page-$i;

if($page >= 1)
$linkPage .= "{$page} ";
}
/*Information of the current page */
if($this->pageNum > 1)
$linkPage .= "{$this->page} ";
 
/*List behind the current page */
for($i=1; $i <= $inum; $i++){
$page = $this->page+$i;
If($page <= $this->pageNum)
$linkPage .= "{$page} ";
else
Break;
}
$linkPage .= '
';
Return $linkPage;
}

/* Private method used inside the object to obtain the operation information of the next page and the last page */
private function nextlast(){
if($this->page != $this->pageNum) {
$str = " {$this->config["next"]} ";
$str .= " {$this->config["last"]}< ;/a> ";
Return $str;
}
}

/* Private method used inside the object to display and process form jump pages */
private function goPage(){
If($this->pageNum > 1) {
return ' ';
}
}

/* Private method used inside the object to obtain the number of records displayed on this page */
private function disnum(){
if($this->total > 0){
Return $this->end()-$this->start()+1;
}else{
Return 0;
}
}
}




This is a very powerful paging class. Although it looks a bit ugly, it can be modified

As for mysql.class.php, I modified the limit method so that it can support one parameter and two parameters, which is more convenient to operate


[php] public function limit($offset,$length=null){
If (is_null($length)) {
           $this->query_list['limit']='limit '.$offset;
         return $this;
}else {
If(!isset($length)){
               $length = $offset;
               $offset = 0;
         } 
                $this->query_list['limit'] = 'limit '.$offset.','.$length;
                    return $this;                               }  

public function limit($offset,$length=null){

if (is_null($length)) {
$this->query_list['limit']='limit '.$offset;
Return $this;
}else {
if(!isset($length)){
$length = $offset;
$offset = 0;
}
$this->query_list['limit'] = 'limit '.$offset.','.$length;
Return $this;
}

Also learned to set the time zone.

[php] date_default_timezone_set("PRC"); //Set time zone (China

date_default_timezone_set("PRC"); //Set time zone (China

Modified the mytpl.class.php template engine so that it will not cause overflow


[php] /**
File: mytpl.class.php The class name is MyTpl, which is a custom template engine
Load the template file through this class object and parse it, and output the parsed result
@Qq496928838
​*/
class MyTpl {
Public $template_dir = 'view'; //Define the directory where template files are stored
Public $compile_dir = 'view_c'; //Define the file storage directory after combining through the template engine
Public $left_delimiter = '<{'; // Embed the left delimiter symbol of dynamic data variables in the template
Public $right_delimiter = '}>'; //Embed the right delimiter of dynamic data variables in the template
          private $tpl_vars = array();                                                                                                                                                                                                                                                                                                                      
/**
The values ​​assigned in PHP will be saved to the member attribute $tpl_vars, which is used to replace the corresponding variables in the board
@Param String $ TPL_VAR requires a string parameter as a associated array. It should correspond to the variable name in the template
​​​​​​​​@param​​mixed​​$value​​​Requires a scalar type value to be assigned to the value of the variable in the template​​​ ​​​​*/
function assign($tpl_var, $value = null) {
If ($tpl_var != ''){
                   $GLOBALS[$tpl_var] = $value;
$this->tpl_vars[$tpl_var] = $value;
                                                                                                                                                                                                                   


         } 
                                   
/**
Load the template file in the specified directory, and store the replaced content to generate the combined file in another specified directory
@param string $fileName Provides the file name of the template file ​​​​*/
function display($fileName) {
                                              /* Search for template files in the specified directory */
$tplFile = $this->template_dir.'/'.$fileName;
/* If the template file to be processed does not exist, exit and report an error */
                if(!file_exists($tplFile)) {                                                         die("Template file {$tplFile} does not exist!");
                                                                                                                                                        /* Get the combined template file, the contents in this file have been replaced */
                 $fileNameMd5 = md5($fileName);

                $comFileName = $this->compile_dir."/com_".$fileNameMd5.'.php';                                              / * Determine whether the file after replacement exists or exists but has changed, you need to re -create * /
If(!file_exists($comFileName) || filemtime($comFileName) < filemtime($tplFile)) {
                                     /* Call the internal replacement template method */
                   $repContent = $this->tpl_replace(file_get_contents($tplFile)); / * Save the script file after the system combination * /
                     file_put_contents($comFileName, $repContent);
                                                                                                                                      /* Contains the processed template file and outputs it to the client */
              include($comFileName);                                    } 
                                   
/**
​​​​​​​A private method used internally, using regular expressions to replace the statements in the template file '<{ }>' with the corresponding values ​​or PHP code
@param string $content Provides the entire content string read from the template file
@Return $ repcontent Return to replacement string
​​​​*/
         private function tpl_replace($content) {
                                      /* Escape the special symbols that have regular effects among the left and right delimiter symbols. For example, <{ }>Escape<{ }> */
                 $left = preg_quote($this->left_delimiter, '/');
                 $right = preg_quote($this->right_delimiter, '/');

/* Pattern array of regular expressions matching various identifiers in the template */
             $pattern = array(                                       / * Matching variables in the template, for example, "& lt; {$ var} & gt;" * /
               '/'.$left.'s*$([a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*)s*'.$right.'/i',                             / * The IF identifier in the matching template, such as "& lt; {if $ color ==" sex "} & gt; & lt; { /if} & gt;" * /
'/'.$left.'s*ifs*(.+?)s*'.$right.'(.+?)'.$left.'s*/ifs*'.$right.'/ies' ,
/ * Match the elseif identifier, such as "& lt; {elseif $ color ==" sex "} & gt;" * /
'/'.$left.'s*elses*ifs*(.+?)s*'.$right.'/ies',
/ * Match the ELSE identifier, such as "& lt; {else} & gt;" * /
‘/’.$left.’s*elses*’.$right.’/is’, 
                        /* Used to match the loop identifier in the template, used to traverse the values ​​in the array, for example "<{ loop $arrs $value }> <{ /loop}>" */
'/'.$left.'s*loops+$(S+)s+$([a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*)s*'.$right.'(. +?)'.$left.'s*/loops*'.$right.'/is',
/ * Used to traverse the keys and values ​​in the array, such as "& lt; {loop $ arrs $ key = & gt; $ value} & gt; & lt; { /loop} & gt;" * /
'/'.$left.'s*loops+$(S+)s+$([a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*)s*=>s*$(S+ )s*'.$right.'(.+?)'.$left.'s*/loop s*'.$right.'/is',
/ * Match the include identifier, for example, '& lt; {include "header.html"} & gt;' * /
                                                                                                                                 " );
                                                                                                /* Replace the string array matched from the template using regular expressions */
$replacement = array(
/ * Replace the variables in the template & lt ;? PHP Echo $ this-& gt; tpl_vars ["var"]; * /
                  'tpl_vars["${1}"]; ?>',                                              /* Replace the if string in the template */
'$this->stripvtags('','${2}')',                                                                                                 / * Replace the string of elseif & lt;? PHP} elseif ($ color == "sex") {? & Gt; * /
‘$this->stripvtags('',"")',
/* Replace else string                    '',                                                          /* The following two items are used to replace the loop identifier in the template with the foreach format */
'tpl_vars["${1}"] as $this->tpl_vars["${2}"]) { ?>${3}', 
'tpl_vars["${1}"] as $this->tpl_vars["${2}"] => $this->tpl_vars["${3 }"]) { ?>${4}', 
/*Replace the include string*/
               'file_get_contents($this->template_dir."/'.$GLOBALS['className'].'/${1}")'
                                                                                );
                                                                                                     /* Use regular replacement function to process */
                $s_content=$content;

               $repContent = preg_replace($pattern, $replacement, $content);                                                                                                                          /* If there are still identifiers to be replaced, recursively call yourself to replace them again */
If(preg_match('/'.$left.'([^('.$right.')]{1,})'.$right.'/', $repContent)) {                             If($s_content==$content) {
                               $repContent = $this->tpl_replace($repContent);
                                                                                                                                                                                                                                                                           /* Return the replaced string */

return $repContent;          } 
                                                                  /**
The private method used inside is used to replace the variable used in the conditional statement to the corresponding value
@Param String $ Expr provided the start marking of conditional statements in the template
                             

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!