您的位置:首页 > 编程语言 > PHP开发

PHP面向对象笔记 —— 116 封装mysql类

2018-03-30 23:33 441 查看
/*

封装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 语句

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面向对象 数据库