mysql类的封装
目标:
连接数据库
发送查询
select 返回查询数据
关闭mysql
传递参数:
1,用配置文件
2,用构造函数传参
class mysql {
private $hos;
private $user;
private $pwd;
private $dbname;
private $conn=null; //用来保存连接的资源
public function __construct(){
//应该是在构造方法里,读取配置文件,然后根据配置文件来设置私有属性,此处还没有配置文件,就直接赋值。
$this->host='localhost';
$this->user='root';
$this->pwd="123456";
$this->dbname='test';
//连接
$this->connect($this->host,$this->user,$this->pwd);
//选库
$this->chosedb($this->dbname);
}
private function connect($h,$u,$p){
$conn=mysql_connect("$h,$u,$p");
$this->conn=$conn;
}
public function query($sql){
//发送sql查询
return mysql_query($sql,$this->conn);
}
public function chosedb($db){
$sql='use' .$db;
mysql_query($sql);
}
public function getall($sql){
$list=array();
$rs=$this->query($sql);
if(!$rs){
return false;}
while($row=mysql_fetch_assoc($rs)){
$list[]=$row;
}
return $list;
}
public function close(){
mysql_close($this->conn)
}
}
$mysql=new mysql();
//print_r($mysql);
$sql="insert into stu values(20,'jjh','999')";
if(!$mysql->query($sql){
echo 'not OK';}
$sql="select * from stu";
$arr=$mysql->getall($sql);