class Db { #结束数据库连接的变量 private $conn = null; #初始化数据库连接信息 public function __construct($db_host='localhost',$db_user='root',$db_pwd='root',$db_name='class15_blog',$port='3306') { #连接数据库 @$this->conn = new mysqli($db_host,$db_user,$db_pwd,$db_name,$port); #判断是否连接成功 if($this->conn->connect_error){ die('数据库连接失败,错误:'.$this->conn->connect_error); } #告诉数据库你的字符编码 @$this->conn->query('SET NAMES UTF8'); } /* *选择数据库 *$db_name string 数据库名 */ public function select_db($db_name){ $this->conn->select_db($db_name); } /* *执行增、删、改是调用 */ public function query($sql){ return $this->conn->query($sql); } /* 获取多条数据,用来执行查询时操作 */ public function getAll($sql){ #执行查询操作 $result = $this->conn->query($sql); #定义返回接收数据的数组 $data = array(); #判断是否有数据 if($result->num_rows){ #循环把数据插入返回的数组中 while($row = $result->fetch_assoc()){ $data[] = $row; } } #返回 return $data; } /* 获取一条数据 */ public function getOne($sql){ #执行查询操作 $result = $this->conn->query($sql); #定义返回接收数据 $data = ''; #判断是否有数据 if($result->num_rows){ #把数据赋给返回的数组 $data=$result->fetch_assoc(); } #返回 return $data; } public function __destruct(){ #如果数据库连接不为空,关闭数据库连接 if($this->conn){ @$this->conn->close(); } } }
原生php连接数据库查询数据
最新推荐文章于 2024-04-22 18:15:02 发布