PHP面向对象笔记 —— 116 封装mysql类
2018-03-30 23:33
441 查看
/*
封装mysql
目标:
连接数据库
发送查询
对于select型 返回查询数据
关闭mysql连接
*/
/*
思路:首先要连接,连接就要有参数.
参数如何传?
1、可以用配置文件,网站大的肯定要有配置文件
2、通过构造函数传参
建议用1,但目前写一个简单类即可.
*/
/*
到此,一个简单的mysql封装类完成.
改进:
insert update操作,都需要大量拼接字符串.
能否给定一个数组
数组键->列
数组值->列的值
然后自动生成 insert 语句
*/
封装mysql
目标:
连接数据库
发送查询
对于select型 返回查询数据
关闭mysql连接
*/
/*
思路:首先要连接,连接就要有参数.
参数如何传?
1、可以用配置文件,网站大的肯定要有配置文件
2、通过构造函数传参
建议用1,但目前写一个简单类即可.
*/
class Mysql { private $host; private $user; private $pwd; private $dbName; private $charset; private $con = null; public function __construct() { // 应该在构造方法里,读取配置文件 // 然后根据配置文件来设置私有属性 // 此处还没有配置文件,就直接赋值 $this->host = 'localhost'; $this->user = 'root'; $this->pwd = ''; $this->dbName = 'test'; // 连接 $this->connect($this->host,$this->user,$this->pwd,$this->dbName); // 切换库 $this->switchDb($this->dbName); // 设置字符集 $this->setChar($this->charset); } // 负责连接 private function connect($h,$u,$v,$p) { $con = mysqli_connect($h,$u,$v,$p); $this->con = $con; } // 负责切换数据库,网站大的时候,可能用到不止一个库 public function switchDb($db) { $sql = 'use' . $db; $this->query($sql); } // 负责设置字符集 public function setChar($char) { $sql = 'set names' . $char; $this->query($sql); } // 负责发送sql查询 public function query($sql) { return mysqli_query($this->con,$sql); } // 负责获取多行多列的select 结果 public function getAll($sql) { $list = array(); $rs = $this->query($sql); if(!$rs) { return false; } while($row = mysqli_fetch_assoc($rs)) { $list[] = $row; } return $list; } // 获取一行的select 结果 public function getRow($sql) { $rs = $this->query($sql); if(!$rs) { return false; } return mysqli_fetch_assoc($rs); } // 获取一个单个的值 public function getOne($sql) { $rs = $this->query($sql); if(!$rs) { return false; } $row = mysqli_fetch_row($rs); return $row[0]; } // 关闭资源 public function close() { mysqli_close($this->con); } } echo '<pre>'; $mysql = new Mysql(); print_r($mysql); /* $s 4000 ql = "insert into stu values(20,'object','6666')"; if($mysql->query($sql)) { echo 'query成功'; } else { echo 'query失败'; } */ echo '<br >'; $sql = 'select * from stu'; $arr = $mysql->getAll($sql); print_r($arr); // 查询79号学员 $sql = 'select * from stu where id=79'; print_r($mysql->getRow($sql)); // 查询共有多少个学生 $sql = 'select count(*) from stu'; print_r($mysql->getOne($sql));
/*
到此,一个简单的mysql封装类完成.
改进:
insert update操作,都需要大量拼接字符串.
能否给定一个数组
数组键->列
数组值->列的值
然后自动生成 insert 语句
*/
相关文章推荐
- php面向对象笔记3 封装和权限修饰符以及继承
- PHP面向对象笔记 —— 113 封装概念
- PHP面向对象笔记
- PHP面向对象学习的笔记
- 我的php学习笔记(十八)php的面向对象开发(五)
- PHP面向对象笔记解析
- PHP面向对象笔记 —— 110 构造函数详解
- 【学习笔记03】java面向对象-封装
- php学习笔记------[PHP面向对象的程序设计]
- PHP 面向对象程序设计(oop)学习笔记(一) - 抽象类、对象接口、instanceof 和契约式编程
- PHP面向对象深入理解之二(封装、继承、多态、克隆)
- php学习笔记 面向对象中[接口]与[多态性]的应用
- PHP面向对象学习笔记之一:基础概念
- PHP面向对象基础笔记二
- PHP面向对象笔记
- PHP面向对象笔记 —— 115 权限控制的bug
- php学习笔记---面向对象中[接口]与[多态性]的应用
- PHP 面向对象笔记
- php面向对象笔记10 异常处理
- PHP 面向对象程序设计(oop)学习笔记 (五) - PHP 命名空间