第3关:方法继承
<?php
class model
{
protected $db; //数据库操作类实例
protected $tableName; //待操作的表名
protected $where; //查询条件
public function __construct($tableName)
{
//实例化数据库
$this->db = new mysqli('127.0.0.1','root','123123');
//获取表名
$this->db->query('set names utf8;');
$this->db->query('use itcast;');
$this->tableName = $tableName;
}
//查询数据
//如果没有指定$this->fields,则查询所有字段
public function where($parames) {
/**********Begin*********/
//定义一个数组变量,用来保存整理后的查询条件
$par_arr = array();
//遍历数组,将数组元素组合成 字段名='字段值'的形式
foreach($parames as $row){
//使用and关键字把查询条件连接成字符串,并赋值给$par_str,注意and前后要有空格
$par_arr[] = "$row[0]$row[2]'$row[1]'";
}
$par_str = implode(' and ',$par_arr);
$this->where = ' where '.$par_str;
//使用where关键字拼接查询条件,并赋值给类的成员属性$where
/**********End*********/
return $this;
}
public function select() {
/**********Begin*********/
//把查询条件拼接到SQL语句中,用变量$sql保存
$sql = "select * from $this->tableName";
$sql .= $this->where;
$this->where = null;
/**********End*********/
$result=$this->db->query($sql);
return $result->fetch_all();
}
}