查询类
实例
<?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;
运行实例 »
点击 "运行实例" 按钮查看在线实例