模板引擎-smarty

一、使用Smarty模板
1、测试安装

$tpl->testInstall();
Smarty Installation test...
Testing template directory...
/mnt/hgfs/study.com/smarty/templates is OK.
Testing compile directory...
/mnt/hgfs/study.com/smarty/templates_c is OK.
Testing plugins directory...
/mnt/hgfs/study.com/smarty/libs/plugins is OK.
Testing cache directory...
/mnt/hgfs/study.com/smarty/cache is OK.
Testing configs directory...
/mnt/hgfs/study.com/smarty/configs is OK.
Testing sysplugin files...
... OK
Testing plugin files...
... OK
Tests complete.

2、初始配置

注意:定界符 和css冲突

$smarty->template_dir = 'templates';   //配置模板所在目录
$smarty->compile_dir  = 'templates_c'; // 编译后文件存储目录
$smarty->config_dir   = 'configs';    // 配置文件目录
$smarty->cache_dir    = 'cache';       //缓存目录
$smarty->left_delimiter='<{';
$smarty->right_delimiter='}>';
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;

$smarty->assign('title','第一次学习Smarty,好紧张啊...');        //看下面test.tpl中内容
$smarty->assign('color','red');        //看下面test.tpl中内容
$smarty->assign('content','测试成功没有!');

二、Smarty的表现逻辑

1、注释

html注释在页面源码中可见,而smarty注释则不能

{config_load file="test.conf" section="setup"}
{include file="header.tpl" title=foo}
<PRE>
{* 从配置文件读取粗体和标题 *}
{if #bold#}<b>{/if}

2、声明变量

通过assign在模板中声明变量
直接通过$变量名称=值,声明变量并且赋值

{assign var=num value=1000}
{$num}
{$name = 'hello'}
{$name}

==注意:变量命名要符合变量命名规则==

3、常用变量修饰符

capitalize [首字母大写] 
count_characters [计算字符数] 
cat [连接字符串] 
count_paragraphs [计算段落数]
count_sentences [计算句数]
count_words [计算词数]
date_format [时间格式]
default [默认]
escape [转码]
indent[缩进]
lower[小写 ]
nl2br[换行符替换成<br />]
regex_replace[正则替换]
replace[替换]PHP面向对象面试题一

PHP面试题
1、写出php的三种访问控制模式的区别
答:public:表示公共的,在本类中和子类中以及类外,可以对其调用;
    private:私有的,不能调用只能在它的本身中调用;
    protected:表示受保护的,可以在本类中和子类中调用
2、借助继承,我们可以创建其他类的派类。在PHP中。子类最多可以继承几个父类
      答:一个;
3、根据需求写代码
  1.定义一个类:A:其中有一个成员属性name
  2.定义一个类:B:继承A
  3.实例化A的类不能直接访问或修改name值
  4.在B类中定义一个print_var方法,该方法返回A类的name值
  5.实例化B,并调用print_var,写出返回值
<?php
    class A{
      protected $name = 'zhangsan';
    }
    class B extends A{
      public function print_var(){
        return $this -> name;
      }
    }

    $a = new A();
    $b = new B();
    echo $b -> print_var();
?>
5、请写出至少7个PHP中魔术方法并说明各自的用户法
  答:__construct(构造函数):构造方法是实例化对象的时候自动执行的方法,作用就是初始化对象。该方法可以没有参数,也可有多个参数,那么在实例化这个对象的时候就要填上相对应的参数,

  __toString():当程序使用echo和print输出时对象,会自动调用该方法目的是希望无参数,但是该方法必须有返回值

  __autoload():当程序执行到实例化的某个类的时候。如果在实例化前没有引用这个类就会执行__autoload()这个函数

  __destruct(析构函数):析构方法作用和构造方法正好相反,是对象被销毁时被调用的作用是释放内存,析构方法没有参数

  __call():当程序调用一个不存在或不可见的成员属性时会自动执行__call(),它有两个参数,分别是未访问到的方法名称和方法的参数,而第二个参数是数组类型

  __set():当程序试图写入一个未定义的或不可见的成员属性时,PHP就会自动执行__set().它包含了两个参数,分别表示属性名和属性值

  __get():当程序调用一个未定义的或不可见的成员属性是,会自动触发执行__get()它有一个参数,表示要调用的属性名称

  __clone():当程序clone一个对象的时候,能触发__clone()方法
6、请以代码的形式体现以下问题
  1.如何声明一个名为''myclass''的没有方法和属性的类?
  2.如何实例化一个名为''myclass''的对象
  3.如何给私有的属性赋值 至少写出2中方法体现
  class myclass
 {
    public function __set($name,$value){
        $this->$name = $value;
    }
    public function func($value){
        $this->temp = $value;
    }
    public function ss(){
        echo $this->temp;
    }
  }
    $kun = new myclass();
    $kun -> temp = 154212;
    $kun -> ss();
7、类的属性可以序列化后保存到session中,从而可以恢复整个类,这要用到的函数是
   答:session_start()/开启会话
       serialize() /序列化
       unserialize()/反序列化
8、根据需求写代码
  1.定义一个类:A,A中有一个disName的方法,方法中输出''AAA''
  2.定义一个类:B,B中有一个disName的方法,方法中输出''BBB''
  3.B类继承A
  4.实例化B,并调用对象disName方法
  5.写出输出
  <?php
      class A{
      public function disName(){
        echo 'AAA';
      }
    }
    class B extends A{
      public function disName(){
        echo 'BBB';
      }
    }
    $a = new B;
    $a -> disName();  //重写A类
    //输出BBB
  ?>
9、接口和抽象类的区别是什么?
     1.抽象类中可以有非抽象的方法而接口中只能有抽象的方法
     2.一个类可以继承多个接口,而一个接口只能继承一个抽象类
     3.接口的使用时通过implements关键字进行,抽象类则是通过extends关键字来进行的


     1、关键字:
        接口:interface 
        实现implements  
        抽象类:abstract 
        继承 extends。接口也可以继承。
    2、接口内不能有成员属性,但是可以有类常量。  抽象类可以声明各种类型成员属性
    3、接口里不能有构造函数,抽象类可以有
    4、接口中的方法只能是public,抽象类三种都有
    5、一个类可以实现多个接口。但是却只能继承一个类


10、类中如何定义常量,如何类中调用常量,如何在类外调用常量
        答:类中的常量也就是成员属性常量,处理就是不会改变的量;定义常量的关键字是const;
        例如:const PI = 3.14;
        无论是类内还是类外常量的访问和变量是不一样的,常量不需要实例化对象,访问常量的格式都是累名
        价作用域操作符(双::号来)来调用 。即:类名 :: 类常量名
        self::PI; 只能在它本身内调用
        static::PI;不能在class外调用
        A::PI;不可以在内里调用
    例如:
      class A{
         const PI = 3.14159;   
      }
        echo A::PI;//不能在类里访问
11、在PHP的面向对象中,类中的定义的析构函数是在()调用的
     答:在代码执行结束后调用
     析构函数不是必须的,当一个类被实例化的时候(如果有)就会被调用,它是用来释放内存的

    spacify[插空]
    string_format[字符串格式化]
    strip[去除(多余空格)]
    strip_tags[去除html标签]
    truncate[截取]
    upper[大写]
    wordwrap[行宽约束]

模板代码

1.tol.class.php页面

<?php
/*
编写一个模板引擎类。
需求:
1、能替换{$name} <?php echo $name;?>
2、通过修改成员属性 可以修改 左右定界符,模板文件的后缀。 
3、通过魔术方法set、get可以设置(获取)模板目录template,编译目录template_c 
4、设置两个默认公共保留变量 {$jack}  =>帅 {$version} =》v1.0
*/
class tpl{
    private   $_template = 'temmplate';  // 需要替换的文本
    private   $compile_file = 'template_c';  // 编译后的文件
    private   $leftMr;
    private   $rightMr;
    private   $prefix = 'php';
    private   $_arr = [];
    public function __construct(){
        $this->a_rr = [
            'title'=> 'smarty模板',
            'jack' => '千斤顶',
            'version' => 'v1.0'
        ];
    }
    public function assign($key,$val){
        $this -> a_rr[$key] = $val;
    }
    //显示文件
    public function dispaly($path){
        extract($this -> a_rr);
        $filename = $this -> _template.'/'.$path;
        $content = file_get_contents($filename);
        $content = str_replace($this->left_delimiter,'<?php echo ',$content);
        $content = str_replace($this->right_delimiter,';?>',$content);
        $file_prefix = pathinfo($filename)['extension'];
        if(!empty($this->prefix)){
            $file_prefix = $this->prefix;
        }
        file_put_contents('template_c/'.pathinfo($path)['filename'].'_c.'.$file_prefix,$content);
        include('template_c/'.pathinfo($path)['filename'].'_c.'.$file_prefix);
    }
    public function __get($name){
        if(isset($this->$name)){
            return $this->$name;
        }
    }
    public function __set($name,$value){
        $this->$name = $value;
    }
}
?>

2.tpl.php页面

<?php
require_once "tpl.class.php";
$Tpl = new tpl();
$Tpl -> left_delimiter = '{#';
$Tpl -> right_delimiter = '#}';
$Tpl -> assign('title','smarty模板');
$Tpl -> assign('name','我的标题');
$Tpl -> dispaly('index.html');
// var_dump($Tpl);
?>

3.html模板

/temmplate/index.html//目录下的index.html页面

<html>
<head>
    <title>{#$name#}</title>
    </head>
<body>
<h1 style="color:red;">{#$title#}</h1>
<hr/ color="red">
<h1>{#$version#}</h1>
<hr/ color="blue">
<h2>{#$jack#}</h2>
<hr/ color="green">
<h1>
<h1>{#$name#}</h1>
<hr/ color="pink">
<h1></h1>
</body>

</html>
/temlate_c/index.html或index.php//目录下的index.html页面
//生成以后的php页面
<html>
<head>
    <title><?php echo $name;?></title>
    </head>
<body>
<h1 style="color:red;"><?php echo $title;?></h1>
<hr/ color="red">
<h1><?php echo $version;?></h1>
<hr/ color="blue">
<h2><?php echo $jack;?></h2>
<hr/ color="green">
<h1>
<h1><?php echo $name;?></h1>
<hr/ color="pink">
<h1></h1>
</body>

</html>

计算器代码

1.index.php

<?php


//异常代码处
class MyException extends Exception
{
    public function Anomalous()
    {
        echo '<h1 style="background-color:red; ">异常页面</h1>';
        echo '<p style="background-color:yellow;">此文件位于:'.$this -> getFile().'</p>'; //返回发生异常信息的文件名
        echo '<br/>';
        echo '<p style="background-color:yellow;">用户传了一个不知道的符号:在 <b style="color:red;">'.$this -> getLine().' </b>行</p><br/>'; // 返回发生异常的代码行号
    }
}
//实现一个计算器 加,减 ,乘, 除
interface iJSQ {
    const MA_JIA   = '+';
    const MA_JIAN  = '-';
    const MA_CHENG = '*';
    const MA_CHU   = '/';
    //加
    public function jia($three,$four);
    //减
    public function jiang($three,$four);
    //乘
    public function chen($three,$four);
    //除
    public function chu($three,$four);
}
class iCalculator implements iJSQ
{
    public $three;
    public $four;
    public function Anomalous($three,$four,$make)
    {
        try{
            if( !is_numeric($three) || !is_numeric($four) )
            {
                throw new MyException('两个值一定是数值型的才可以......');
            }
            switch ( $make ){
                case self::MA_JIA:
                    return $this -> jia($three,$four);
                    break;
                case self::MA_JIAN:
                    return $this -> jiang($three,$four);
                    break;
                case self::MA_CHENG:
                    return $this -> chen($three,$four); 
                    break;
                case self::MA_CHU:
                    return $this -> chu($three,$four);
                    break;
                default:
                    throw new MyException('用户传了一个不认识的符号过来但我不知道怎么处理!!!!');
            }

        }catch( Exception $e ){
            $e -> Anomalous();
            $e -> getLine();
        }
    }
    //加
    public function jia($three,$four)
    {
        return $three + $four;  
    }
    //减
    public function jiang($three,$four)
    {
        return abs($three - $four); 
    }
    //乘
    public function chen($three,$four)
    {
        return abs($three * $four); 
    }
    //除
    public function chu($three,$four)
    {
        return abs($three / $four); 
    }       
}

$my = new iCalculator();
echo '结果是:'.$my -> Anomalous(91,20,'/');
?>

2.jsq.php

<?php
interface iCounter
{
    // 加
    public function jia($One,$two);

    // 减
    public function jiang($three,$four);

    // 乘
    public function cheng($five,$six);

    // 除
    public function chu($seven,$eight);
}
class arithmetic implements iCounter
{
    public function handle($One,$two,$mark){
        try{
            if(!is_numeric($One) || !is_numeric($two)){
                throw new Exception('不是数字'); 
            }
            switch($mark){
                //加法
                case '+':
                    if($One == 0 && $two == 0)
                    {
                        throw new Exception('数字不能0');
                    }else{
                        return $this->jia($One,$two);
                    }
                break;
                //减法
                case '-':
                    if($One == 0 && $two == 0)
                    {
                        throw new Exception('数字不能为0');
                    }else{
                        return $this->jiang($One,$two);
                    }
                break;
                //乘法
                case '*':
                    if($One ==0 && $two == 0)
                    {
                        throw new Exception('数字不能为0');
                    }else{
                        return $this->cheng($One,$two);
                    }
                break;  
                //除法
                case '/':
                    if($One==0 && $two==0)
                    {
                        throw new Exception('除数与被除数都不能为0');
                    }else{
                        return $this->chu($One,$two);
                    }
                break;
            }
        }catch(Exception $e){

            echo $e->getMessage().',错误所在行数:'.$e->getLine();
        }
    }
    // 加法的方法
    public function jia($One,$two)
    {   
        return $One + $two;
    }
    // 减法的方法
    public function jiang($One,$two)
    {
        return $One - $two;
    }
    // 乘法的方法
    public function cheng($One,$two)
    {
        return  $One * $two;
    }
    // 除法的方法
    public function chu($One,$two)
    {
        return  $One / $two;
    }
}
$jisuanqi = new arithmetic;
echo $jisuanqi->handle('12','5','*');

?>

3.数据库代码

<?php
class mysql 
{
    public $link;
    public $name;
    public $db_local;
    public $db_pwd;
    public $user_error;
    public function __construct($db_local,$db_user,$db_pwd,$db_name)
    {
        //这个可以通过构造方法来去读取我们的数据库配置文件
        $this->link = @mysql_connect($db_local,$db_user,$db_pwd) or die('数据库连接失败');
        mysql_select_db($db_name,$this->link);
        mysql_set_charset('utf8',$this->link);
    }
    public function findOne( $tabname, $id )
    {
        $sql = "select * from {$tabname} where id = {$id} ";
        $result = mysql_query($sql,$this->link);
        $list = [];
        if( $result && mysql_affected_rows() > 0 ){
            while( $row = mysql_fetch_assoc($result) )
            {
                $list[] = $row;
                var_dump($list);
            }
            return $list;
        }else{
            return [];
        }
    }
}

$mysql = new mysql('localhost','root','root','hello');
$aList = $mysql->findOne('mysql',1);
?>

4.作业


<table border="1"width="500" height="500" align="center">
<tr>
<td align="center">
<h1 style="color:green;font-size:30px">作 业</h1>
一、编写一个生成金字塔的功能
1、一个表单提交 用于录入金字塔层数<br/>
<form action="" method="post">
    <input type="number" name="text" size="10" />
    <input type="submit" value=" 显示 " name="Submit" />
</form>
<?php
 class pyramid{
    public function __construct($empty,$value){
        if(!empty($_POST['text']) ) {
            //打印正立金字塔
            for( $i = 1; $i <= $empty; $i++ ){
                //打印每一层的空格数
                for( $j = $empty; $j > $i; $j-- ) {
                    echo " ";
                }
                    //打印每一层的星星个数                                                                            
                    for( $k = 1; $k <= $i*2-1; $k++ ) {
                        echo $value;
                    }
                echo '<br/>';
            }
            echo '<hr/>';
        }else{
            echo '<b style="color:green;">你个二逼,只能输入数字,不能输入中文,英文,以及空格哦,下次记住了,不要再输入那些没用的了,我不识别</b>';
        }
    }
}
$empty = isset($_POST['text']) ? $_POST['text'] : 1 ;
$construct = new pyramid($empty,'<b style="color:red;">*</b>');

echo '<br/>';

 echo '二、定义一个字符串(纯数字)生成类:(目的用于生成验证码)<br/>';
class code
{   
    public $nubmer;
    public function __construct($nubmer){  
        for( $one = 0; $one < $nubmer; $one++ ){
            echo '<span style="font-weight:700;font-size:28px;color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).');">'.mt_rand(0,9).'</span>';
        }
    }       
}
$strin = new code(4); 

echo '<hr/>';
/* $nubmer = 4;
$code = '0123456789';
for( $one = 0; $one < $nubmer; $one++ ){
    $string = $code{mt_rand(0,strlen($code)-1)}; 
    echo $string;
}*/
echo '三、定义一个字符串生成类:(目的用于生成验证码)<br/>';
class randnameP{
    public $cedo = 4;
    public $codea = 'c';
    public function fandunam(){
        switch( $this-> codea ){
            case 'a':
                $scandir = "0123456789";
                break;
            case 'b':
                $scandir = "0123456789abcdefghijklmnopqrstuvwxyz";
                break;
            case 'c':
                $scandir = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                break;
            default :
                $scandir = "0123456789";
                break;
        }
        for( $i = 0; $i< $this->cedo; $i++ ){
            echo '<span style="font-weight:700;font-size:28px;color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).');">'.$scandir[mt_rand(0,strlen($scandir)-1)].'</span>';
        }
    }
}
$string = new randnameP();
$string -> fandunam();
echo '<hr/>';

echo '四、用面向对象的方法输出一个表格<br/>
1、成员属性:id,name,sex,nation,birthdy<br/>
2、把对象存入数组<br/>
3、遍历数组生成表格<hr/>';
class xtable 
{
    public $id;
    public $name;
    public $sex;
    public $nation;
    public $birth;

    public function __construct($id,$name,$sex,$nation,$birth){
        $this -> id = $id;
        $this -> name = $name;
        $this -> sex = $sex;
        $this -> nation = $nation;
        $this -> birth = $birth;
    }
}
$xtable2 = new xtable('2','喻恒勇','男','火星','1111-10-1');
$array = [$xtable2];
echo '<table border="1"width="300"height="50">
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>性别</th>
            <th>国家</th>
            <th>出生日期</th>
        </tr>';
    foreach($array as $key => $value){
        echo '<tr>
                <td>'.$value->id.'</td>
                <td>'.$value->name.'</td>
                <td>'.$value->sex.'</td>
                <td>'.$value->nation.'</td>
                <td>'.$value->birth.'</td>
            </tr>
    </table>';
}
?>
</td>
</tr>
</table>

4.分页

<?php
/* ================================================
 *   @类名:   Page                                *
 *   @参数:   $myde_total  总记录数                *
 *            $myde_size   页显示的记录数          *
 *            $myde_page   当前页                 *
 *   @功能:   分页实战                             *
 *=================================================
 */
class Page {
    public $myde_total;          //总记录数
    public $myde_size;           //每页显示的多少条
    public $myde_page_count;     //总页数
    public $myde_i;              //当前第几页
    public $myde_en = 2;         //页面两边的数字

    /*===================================
     *                                  *
     *              页面显示             *
     *                                  *
     *              构造函数             *
     *                                  *
     *====================================*/

    public function __construct($myde_total ,$myde_size, $myde_i ) {

        $this -> myde_total = $myde_total;
        $this -> myde_size  = $myde_size;      
        $this -> myde_page_count = ceil($this -> myde_total / $this->myde_size);
        if($myde_i < 0){
            $this -> myde_i  = 1;
        }else if($myde_i > $this->myde_page_count){
            $this -> myde_i  = $this->myde_page_count;
        }else{
             $this -> myde_i  = $myde_i;
        }
    }
    //获取首页
    public function myde_home() 
    {
        if ($this -> myde_i > 1) {
            return "<a href='page.php'>首页</a>";
        }
            return "<p>首页</p>"; 
    }
    //获取上一页
    public function myde_prev() 
    {
        if( $this->myde_i >1 ){
            return '<a href="page.php?page='.($this->myde_i-1).'">上一页</a>';
        }
            return '<p>上一页</p>';
    }
    /**
    *
    *获取下一页
    */
    public function myde_next() 
    {
       if( $this->myde_i < $this-> myde_page_count ){
            return '<a href="page.php?page='.($this -> myde_i + 1).'">下一页</a>';
        }
            return '<p>下一页</p>';
    }
    //获取尾页
    public function myde_last() 
    {   
        if ( $this -> myde_i < $this -> myde_page_count ) {
            return '<a href="page.php?page='.($this->myde_page_count).'" >尾页</a>';
        }
            return "<p>尾页</p>"; 
    }
    //实现多少页
    public function code()
    {
        return '<p class="pageRemark">共<b>'.$this->myde_page_count.'</p>页';
    }
    //获取每一条数据
    public function sum()
    {
        return '<b>'.$this -> myde_total.'</b>条数据</p>';
    }

    public function start()
    {
        $achieve = '';
        if( $this -> myde_i - $this -> myde_en > 1 )
        {
            $achieve .= "<p class='pageEllipsis'>...</p>";

            for( $i = $this -> myde_i - $this -> myde_en; $i  < $this -> myde_i;$i++)
            {
                $achieve .= '<a href="page.php?page='.$i.'">'.$i.'</a>';
            }
        }else{
            for( $i =1;$i <= $this->myde_i-1;$i++){
                $achieve .= '<a href="page.php?page='.$i.'">'.$i.'</a>';
            }
        }
        $achieve .= '<a href="" class="cur">'.$this -> myde_i.'</a>';

        if( $this-> myde_i + $this -> myde_en < $this -> myde_page_count ){
            for( $k = $this -> myde_i + 1; $k <= $this -> myde_i + $this -> myde_en;$k++ ){
                $achieve .= '<a href="page.php?page='.$k.'">'.$k.'</a>';
            }
            $achieve .= "<p class='pageEllipsis'>...</p>";
        }else{
            for( $j = $this -> myde_i + 1; $j <= $this -> myde_page_count; $j++ ){
                $achieve .= '<a href="page.php?page='.$j.'">'.$j.'</a>';
            }
        }
            return $achieve;
        }
    //用来显示
    public function Show()
    {
        $paged = '<div id="page">';
        $paged .= $this -> myde_home();
        $paged .= $this -> myde_prev();
        $paged .= $this -> start();
        $paged .= $this -> myde_next();
        $paged .= $this -> myde_last();
        $paged .= '</div>';
        return $paged;
    }
}  

$pageted = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$pad = new Page(50,5,$pageted);
echo $pad -> Show();

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
      <style type="text/css">
            p{margin:0}
            #page{
                height:40px;
                padding:20px 0px;
            }
            #page a{
                display:block;
                float:left;
                margin-right:10px;
                padding:2px 12px;
                height:24px;
                border:1px #cccccc solid;
                background:#fff;
                text-decoration:none;
                color:#808080;
                font-size:12px;
                line-height:24px;
            }
            #page a:hover{
                color:#077ee3;
                border:1px #077ee3 solid;
            }
            #page a.cur{
                border:none;
                background:#077ee3;
                color:#fff;
            }
            #page p{
                float:left;
                padding:2px 12px;
                font-size:12px;
                height:24px;
                line-height:24px;
                color:#bbb;
                border:1px #ccc solid;
                background:#fcfcfc;
                margin-right:8px;

            }
            #page p.pageRemark{
                border-style:none;
                background:none;
                margin-right:0px;
                padding:4px 0px;
                color:#666;
            }
            #page p.pageRemark b{
                color:red;
            }
            #page p.pageEllipsis{
                border-style:none;
                background:none;
                padding:4px 0px;
                color:#808080;
            }
            .dates li {font-size: 14px;margin:20px 0}
            .dates li span{float:right}
        </style>
</head>
</body>
</html>

5.域名修改

$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

 if( preg_match_all('/\/[0-2]+\/[0-9]+\.html$/',$url) )
 {
     preg_match_all('/[0-9]+/',$url,$match);
     $url = 'index.php?type='.$match[0][0].'&id='.$match[0][1];
     var_dump($url);
     echo '<script>location.href="'.$url.'"</script>';

     } 

 $url = 'http://study.com/index.php/12/2.html';
 if( preg_match_all('/\/[0-2]+\/[0-9]+\.html$/',$url) )
 {
     preg_match_all('/[0-9]+/',$url,$match);
     preg_match('/http[s]?\:\/\/([a-zA-Z])+.[com|cn|net|org]+[\/\w*]+.[php]+/',$url,$match2);
     $url = $match2[0];
     $url .= '?type='.$match[0][0].'&id='.$match[0][1];
     var_dump($url);
 }

6.生成数据库字典

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自动生成数据字典</title>
    <style>
        body,td,th {font-family:"宋体"; font-size:12px;}
        table,h1,p{width:960px;margin:0px auto;}
        table{border-collapse:collapse;border:1px solid #CCC;background:#efefef;}
        table caption{text-align:left; background-color:#fff; line-height:2em; font-size:14px; font-weight:bold; }
        table th{text-align:left; font-weight:bold;height:26px; line-height:26px; font-size:12px; border:1px solid #CCC;padding-left:5px;}
        table td{height:20px; font-size:12px; border:1px solid #CCC;background-color:#fff;padding-left:5px;}
        .c1{ width: 150px;}
        .c2{ width: 150px;}
        .c3{ width: 80px;}
        .c4{ width: 100px;}
        .c5{ width: 100px;}
        .c6{ width: 300px;}
        select{
               margin-left: 620px;
        }
    </style>
    <!--
    SELECT * FROM information_schema.`TABLES` WHERE table_name = 'tasks' AND table_schema = 'dbname';

    SELECT * FROM information_schema.`COLUMNS` WHERE table_name = 'tasks' AND table_schema = 'dbname';
    -->

</head>
<body style="background-color:#aaa;">
    <h1 style="text-align:center;color:red;width:100px">数据字典</h1>
    <p style="text-align:center;margin:20px auto;">生成时间:<?php  date_default_timezone_set('Asia/shanghai'); echo date('Y-m-d H:i:s',time())?></p>
    <form method="post">
    <select id="option" name="select">
        <?php
            $link = @mysql_connect('localhost','root','root');
            if(mysql_errno()){
                file_put_contents('erron.log',mysql_error());
            }

            mysql_set_charset('utf8');

            $zidian = mysql_query("select * from information_schema.TABLES group by TABLE_SCHEMA having TABLE_SCHEMA not in('mysql','performance_schema','information_schema')");
            while(($qude = mysql_fetch_assoc($zidian)) != false){
        ?>
        <option value="<?php echo $qude['TABLE_SCHEMA']?>"<?php if(!empty($_POST['select']) && $_POST['select']==$qude['TABLE_SCHEMA']){echo 'selected="selected"';}?>><?php echo $qude['TABLE_SCHEMA']?></option>
        <?php }?>
    </select>
    <input type="submit" name="sub" value=" query "/>
    </form> <hr/>

    <?php
        $rest = !empty($_POST['select']) ? $_POST['select'] : 'blog';
        $query = mysql_query("select * from information_schema.tables where table_schema ='{$rest}'");
        while(($fech = mysql_fetch_assoc($query)) != false){
    ?>

    <table border="1" cellspacing="0" cellpadding="0" align="center">
        <caption>表名:<?php echo $fech['TABLE_NAME'];?> </caption>
        <tbody>
        <tr>
            <th>字段名</th>
            <th>数据类型</th>
            <th>默认值</th>
            <th>允许非空</th>
            <th>自动递增</th>
            <th>备注</th>
        </tr>
            <?php
                $sql_regcase = mysql_query("select * from information_schema.columns where table_name ='{$fech['TABLE_NAME']}'");
                while(($mt_srand = mysql_fetch_assoc($sql_regcase)) !=false){
            ?>
        <tr>
            <td class="c1"><?php echo $mt_srand['COLUMN_NAME'];?></td>
            <td class="c2"><?php echo $mt_srand['COLUMN_TYPE'];?></td>
            <td class="c3"><?php echo $mt_srand['COLUMN_DEFAULT'];?></td>
            <td class="c4"><?php echo $mt_srand['IS_NULLABLE'];?></td>
            <td class="c5"><?php echo $mt_srand['EXTRA'];?></td>
            <td class="c6"><?php echo $mt_srand['COLUMN_COMMENT'];?></td>
        </tr>
            <?php
                }
            ?>
        </tbody>
    </table>
    <?php
            }
    ?>
</body>
</html>

7.数据库作业

<?php
class MySQL
{
    public $aFields = []; // 存储表里面所有字段
    protected $link; // 数据库连接
    private $_array = [
        'db_host' => 'localhost', //主机地址
        'db_user' => 'root', //用户名
        'db_pwd'  => 'root',//用户密码
        'db_name' => 'hello',//数据库名
        'db_charset' => 'utf8'//数据库编码
    ];
    private $_tablname; //表名
    private $_tabPre = 'pc_'; //表名前缀
    private $_lj; //表主键字段

    //构造
    public function __construct( $tabname ){
        extract($this->_array);
        $this->link= @mysql_connect($db_host,$db_user,$db_pwd) or die('数据库连接失败');//数据库连接
        @mysql_select_db($db_name,$this->link);//数据库名字
        @mysql_set_charset($db_charset,$this->link);
        $this->_tablname = $this->_tabPre.$tabname;
        $this->getTableFields($this->_tablname);

        if( mysql_errno() ){
            $error = "错误信息是: ".mysql_errno().":错误信息是:".mysql_error();//错误日志
        }else{
            return false;       
        }
    }

    /**
     * 更新记录
     * @param number $id
     * @param array $post
     */
    public function update($id, array $post ){
        $sql = "UPDATE $this->_tablname SET ";
        $set = [];
        foreach($post as $key => $value){
            $set[] = "`{$key}`='{$value}'";
        }
        $sql .= implode(',', $set);
        $sql .= " WHERE $this->_lj = {$id}";
        echo $sql;
        $sest = mysql_query($sql);
        if( $sest && mysql_affected_rows() ){
            return mysql_affected_rows();
        }else{
            return false;   
        }
    }

    /**
     * 获取单条记录
     * @param number $id
     * @return array
     */
    public function find($id){
        $sql = "SELECT * FROM $this->_tablname WHERE {$this->_lj}='{$id}'";//获取单条记录
        //echo $sql;
        $sest = mysql_query($sql);
        $rows = [];
        if( $sest && mysql_affected_rows()>0 ){
            $rows = mysql_fetch_assoc($sest);
        }else{
            return $rows;
        }
    }

    /**
     * 插入数据
     * @param array $post
     */
    public function insert(array $post){
        $query  = '';
        $query .= "insert into `$this->_tablname`";
        $query .= "(`".implode('`,`', array_keys($post))."`)";
        $query .= ' values ';
        $query .= "('".implode('\',\'', array_values($post))."')";
        //var_dump($query);
        $sest = mysql_query($query,$this->link);
        if( $sest && mysql_affected_rows() > 0 ){
            return mysql_insert_id();
        }else{
            return false;
        }
    }

    /**
     * 获取全部记录
     * @param array $post
     * @return arraylist
     */
    public function findAll(array $aCondition=[]){
        $sql = $this-> handleCondition($aCondition);
        //echo $sql;
        //return $sql;
        //$sql ="SELECT title,content FROM pc_ddg ORDER BY id DESC LIMIT 1,4;";
        $Ambigous = mysql_query($sql);
        //var_dump($Ambigous);
        $words = [];
        if($Ambigous && mysql_affected_rows() > 0){
            while($word = mysql_fetch_assoc($Ambigous) ){
                $words[]  = $word;
            }
            return $words;
        }else{
            return false;
        }
    }   

    /**
     * 删除记录
     * @param number $id
     */
    public function delete( $id ){
    $sql = "delete from $this->_tablname where {$this->_lj} = {$id}";
        echo $sql;
        $sest = mysql_query($sql);
        if( $sest == mysql_affected_rows() ){
            return mysql_affected_rows();
        }else{
            return false;
        }
    }

    /**
     * 处理查询条件
     * @param array $aCondition  []
     */
    protected function handleCondition(array $aCondition){
        if( !empty($aCondition) ){
            $sele = '*';
            $limit = $order = '';
            foreach ($aCondition as $key=>$value){
                $key = strtolower($key);
                switch ($key){
                    case 'select':  
                        $sele = $value;
                    break;
                    case 'sort':
                        $order = ' order by '.$value;
                    break;  
                    case 'limit':
                        $limit = ' limit '.$value;
                    break;  
                }
            }
            $sql = "SELECT $sele FROM $this->_tablname{$order}{$limit}";
        }else{
            $sql = "SELECT * FROM $this->_tablname";
        }
        return $sql;
    }

    /**
     * 获取表主键字段
     * @return Ambigous <>|string
     */
    protected function getTableFields(){
        $sql = "desc $this->_tablname";
        $sest = mysql_query($sql);
        if( $sest && mysql_affected_rows() > 0 ){
            while ($row = mysql_fetch_assoc($sest)) {
                if( $row['Key'] == 'PRI' )
                    $this->_lj = $row['Field'];
                    $this->aFields[] = $row['Field'];
            }
        }else{
            return false;
        }
    }
}

$my = new MySQL('dd');

//插入数据
//$my -> insert(['title'=>'张三','content'=>'李四','created'=>'2017-4-20 12:00:00']);

//修改数据
//var_dump($my -> update(4,['title'=>'李四']));

//删除
//var_dump($my->delete(4));

//查询单条
//var_dump($my->find(3));

//查询全部
var_dump($my -> findAll(['select'=>'title,content,created','limit'=>'0,4','sort'=>'id DESC']));
发布了23 篇原创文章 · 获赞 28 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章