Blogger Information
Blog 28
fans 0
comment 0
visits 15743
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
2018-09-04数据库的链式操作
阿小的博客
Original
479 people have browsed it

查询类

实例

<?php
class Query
{
    private $pdo = null;
    private $sql = [];
    
    public function __construct()
    {
        $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=guest', 'root', '123456');
    }
    
    public function table($table)
    {
        $this->sql['table'] = $table;
        return $this;       //返回当前数组实例对象,便于链式调用该对象的其他方法
    }
    
    public function fields($fields)
    {
        $this->sql['fields'] = $fields;
        return $this;
    }
    
    public function where($where)
    {
        $this->sql['where'] = $where;
        return $this;
    }
    
    public function select()
    {
        $this->sql = "SELECT {$this->sql['fields']} FROM {$this->sql['table']} WHERE {$this->sql['where']}";
        $stmt = $this->pdo->prepare($this->sql);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

实现类

实例

<?php
//实现方法的跨类调用
//实现数据库的链式操作
// //call_user_func_array回调函数
// call_user_func_array($function, $param_arr);
// call_user_func_array([$obj,$name], $param_arr);
// call_user_func_array([Class,$name], $param_arr);
require 'Query.php';

class Db
{
    public static function __callStatic($name,$param_arr)
    {
       return call_user_func_array([(new Query()),$name], $param_arr);
    }   
}
$result = Db::table('g_users')->fields('G_ID,G_UserName,G_Sex,G_Email')->where("G_ID>'10'")->select();
//var_dump($result);
$table ='<table width=800 border=1 cellspacing=0>';
foreach ($result as $row)
{
    $table .= '<tr align="center">';
    $table .= '<td>'.$row['G_ID'].'</td>';
    $table .= '<td>'.$row['G_UserName'].'</td>';
    $table .= '<td>'.$row['G_Sex'].'</td>';
    $table .= '<td>'.$row['G_Email'].'</td>';
    $table .= '</tr>';
}

$table .= '</table>';
echo $table;

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post