======简单MySql类封装=======
目标:
链接数据库,
发送查询
对于select型,返回查询数据
关闭mysql链接
思路:首先得链接,链接就得有参数
参数如何传?
答:
1.可以用配置文件,当网站大了,肯定会有配置文件
2.可以通过构造函数传参
建议用1,但我们目前,仅仅是写一个简单类
<?php
class Mysql
{
private $host;
private $user;
private $pwd;
private $dbName;
private $charset;
private $conn = null;//保存服务器连接的资源
public function __construct()
{
/*应该在构造方法里,读取配置文件
然后根据配置文件来设置私有属性
此处还没有配置文件,就直接赋值了
*/
$this->host = 'localhost';
$this->user = 'root';
$this->pwd = '';
$this->dbName = 'test';
$this->charset = 'utf8';
//链接
$this->connect($this->host,$this->user,$this->pwd);
//切换库
$this->switchDb($this->dbName);
//设置字符集
$this->setChar($this->charset);
}
//负责链接
private function connect($h,$u,$p){
$conn = mysqli_connect($h,$u,$p);
$this->conn = $conn;
}
//负责切换数据,网站大的时候,可能用到不止一个库
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($sql,$this->conn);
}
//负责获取多行多列的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->conn);
}
}
echo "<pre>";
$mysql = new Mysql();
print_r($mysql);
/*
$sql = "insert into boy (hid,bname) values('D','王宝强')";
$result = $mysql->query($sql);
if ($result) {
echo "query successfuly";
} else {
echo mysql_errno();
}
*/
$sql = 'select * from boy';
$result = $mysql->getAll($sql);
echo "<hr>";
//查询hid=C 男人
$sql = "select * from boy where hid = 'C'";
print_r($mysql->getRow($sql));
echo "<hr>";
//查询共有多少男人
$sql = 'select count(*) from boy';
print_r($mysql->getOne($sql));
echo "</pre>";
到此,一个简单的mysql封装类,完成.
改进:
insert update 操作,都需要大量拼接字符串
能够给定一个数组,数组键->列,数组值->列的值
然后自动生成insert语句.