简单的mysql封装类

class mysql{
private $host;
private $user;
private $pwd;
private $dbname;
private $charset;
private $conn=null;//保存连接的资源
public function __construct(){
//应该是在构造方法里读取配置文件
//然后根据配置文件来设置私有属性
//此处还没有配置文件,就直接赋值
$this->host='127.0.0.1';
$this->user='root';
$this->pwd='';
$this->dbname='test';
//连接
$this->connect($this->host,$this->user,$this->pwd);
//切换库
$this->switchdb($this->dbname);
//设置字符集
$this->setchar($this->charset);
}
//负责连接
private function connect($host,$user,$pwd){
$conn=mysql_connect($host,$user,$pwd);
$this->conn=$conn;
}
//负责切换数据库,网站大的时候,可能用到不止一个库
public function switchdb($dbname){
$sql='use '.$dbname;
$this->query($sql);
}
//负责设置字符集
public function setchar($char){
$sql='set names'.$char;
$this->query($sql);
}
//负责发送sql查询
public function query($sql){
return mysql_query($sql,$this->conn);
}
//负责获取多行多列的select结果
public function getall($sql){
$list=array();
$rs=$this->query($sql);
if(!$rs){
return false;
}
while($row=mysql_fetch_assoc($rs)){
$list[]=$row;
}
return $list;
}
//获取一行的select结果
public function getrow($sql){
$rs=$this->query($sql);
if(!$rs){
return false;
}
return mysql_fetch_assoc($rs);
}
//获取一个单个的值
public function getone($sql){
$rs=$this->query($sql);
if(!$rs){
return false;
}
return mysql_fetch_row($rs);
return $row[0];
}
public function close(){
mysql_close($this->conn);
}
}
$mysql=new mysql();
print_r($mysql);

echo '
';
$sql="select*from stu";
$arr=$mysql->getall($sql);
var_dump($arr);

//查询2号学员
$sql='select*from stu where id=2';
var_dump($mysql->getrow($sql));

//查询共有多少个学员
$sql='select count(*) from stu';
var_dump($mysql->getone($sql));

原文地址:https://www.cnblogs.com/suiyuewuxin/p/5608487.html