1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| class Db_Mysql {
//数据库连接对象 protected $_conn;
//初始化数据库连接 public function __construct($host, $user, $pass, $dbName) { $dsn = "mysql:host={$host};dbname={$dbName}"; $option = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''); $this->_conn = new PDO($dsn, 'root', '',$option); }
//插入操作 public function insert($data) { //传入一个数组,可以插入数据 }
//修改操作 public function update($data, $where) { //根据查询条件,修改数据 }
//删除操作 public function delete($where) { //根据查询条件,删除数据 }
//执行sql操作 public function exec($sql) { $this->getConnection()->exec($sql); }
//查询操作 public function query($sql) { $data = $this->getConnection()->query($sql); $data->setFetchMode(PDO::FETCH_ASSOC); $res = $data->fetchAll(); return $res; }
//获取连接 public function getConnection() { return $this->_conn; } }
class Test extends Db_Mysql {
//初始化 public function __construct($host, $user, $tableName, $pass) { parent::__construct($host, $user, $pass, $tableName); } }
//查询 $test = new Test('127.0.0.1', 'root','test',''); $sql = "select * from user limit 1"; $res = $test->query($sql); var_dump($res); //执行 $sql = "SET NAMES utf8"; $res = $test->exec($sql); var_dump($res);
|