先前有过文章介绍了PHP中通过普通方法对mysql进行封装使用,回顾可以点击链接查看: PHP中MySQL的连接封装。今天介绍使用类的方法对MySQL进行封装。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
header("content-type:text/html;
charset=utf8");
//Mysql数据库连接
class Mysql {
public $db_host;
public $db_user;
public $db_pass;
public $db_charset;
public $db_name;
public function __construct($db_host,$db_user,$db_pass,$db_charset,$db_name) {
$this->db_host=$db_host;
$this->db_user=$db_user;
$this->db_pass=$db_pass;
$this->db_charset=$db_charset;
$this->db_name=$db_name;
$this->connect();
}
public function connect() {
@mysql_connect($this->db_host,$this->db_user,$this->db_pass);
mysql_set_charset($this->db_charset);
mysql_select_db($this->db_name);
}
public function getAll($sql) {
$res =mysql_query($sql);
$rows=[];
while($row=mysql_fetch_assoc($res)) {
$rows[]=$row;
}
return $rows;
}
public function __destruct() {
mysql_close();
}
}
$mysql=new Mysql('127.0.0.1','root','root','utf8','cms');
$arr=$mysql->getAll("select *from cms_user");
var_dump($arr);
?>

本文早期发布于个人 CSDN 博客:查看原文

站内搜索

没有找到内容!