一、建立mysql_class.php文件而后在该文件中建立Mysql类,并定义变量php
1
2
3
4
5
6
7
8
9
10
11
|
<?php
class Mysql{
private $host;//服务器地址
private $root;//用户名
private $password;//密码
private $database;//数据库名
//后面所提到的各个方法都放在这个类里
//...
}
?>
|
二、经过构造函数初始化类css
1
2
3
4
5
6
7
|
function __construct($host,$root,$password,$database){
$this->host = $host;
$this->root = $root;
$this->password = $password;
$this->database = $database;
$this->connect();
}
|
对于connect()方法,下一步再说mysql
三、建立链接数据库及关闭数据库方法web
1
2
3
4
5
6
7
8
9
|
function connect(){
$this->conn = mysql_connect($this->host,$this->root,$this->password) or die(
"DB Connnection Error !"
.mysql_error());
mysql_select_db($this->database,$this->conn);
mysql_query(
"set names utf8"
);
}
function dbClose(){
mysql_close($this->conn);
}
|
四、对mysql_query()、mysql_fetch_array()、mysql_num_rows()函数进行封装sql
1
2
3
4
5
6
7
8
9
10
11
|
function query($sql){
return mysql_query($sql);
}
function myArray($result){
return mysql_fetch_array($result);
}
function rows($result){
return mysql_num_rows($result);
}
|
五、自定义查询数据方法数据库
1
2
3
|
function select($tableName,$condition){
return $this->query(
"SELECT * FROM $tableName $condition"
);
}
|
六、自定义插入数据方法服务器
1
2
3
|
function insert($tableName,$fields,$value){
$this->query(
"INSERT INTO $tableName $fields VALUES$value"
);
}
|
七、自定义修改数据方法函数
1
2
3
|
function update($tableName,$change,$condition){
$this->query(
"UPDATE $tableName SET $change $condition"
);
}
|
八、自定义删除数据方法fetch
1
2
3
|
function delete($tableName,$condition){
$this->query(
"DELETE FROM $tableName $condition"
);
}
|
如今,数据库操做类已经封装好了,下面咱们就来看看该怎么使用。ui
咱们用的仍是在PHP链接数据库,实现最基本的增删改查(面向过程)一文中所涉及到的数据库及表(表中数据本身添加):
九、那么咱们先对数据库操做类进行实例化
1
|
$db = new Mysql(
"localhost"
,
"root"
,
"admin"
,
"beyondweb_test"
);
|
实例化能够在mysql_class.php文件中的Mysql类以外进行。
而后咱们再建立一个test.php文件,首先把mysql_class.php文件引入
1
2
3
|
<?php
require(
"mysql_class.php"
);
?>
|
而后咱们就开始操做吧
十、向表中插入数据
1
2
3
4
|
<?php
$insert = $db->insert(
"user"
,
"(nikename,email)"
,
"(#beyondweb#,#beyondwebcn@xx.com#)"
);//请把#号替换为单引号
$db->dbClose();
?>
|
十一、修改表中数据
1
2
3
4
|
<?php
$update = $db->update(
"user"
,
"nikename = #beyondwebcn#"
,
"where id = #2#"
);//请把#号替换为单引号
$db->dbClose();
?>
|
十二、查询表中数据并输出
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
|
<?php
$select = $db->select(
"user"
);
$row = $db->rows($select);
if($row>=
1
){
?>
<table border=
"1px"
>
<tr>
<th>id</th>
<th>nikename</th>
<th>email</th>
</tr>
<?php
while($array = $db->myArray($select)){
echo
"<tr>"
;
echo
"<td>"
.$array[#id#].
"</td>"
;//请把#号替换为单引号
echo
"<td>"
.$array[#nikename#].
"</td>"
;//请把#号替换为单引号
echo
"<td>"
.$array[#email#].
"</td>"
;//请把#号替换为单引号
echo
"</tr>"
;
}
?>
</table>
<?php
}else{
echo
"查不到任何数据!"
;
}
$db->dbClose();
?>
|
1三、删除表中数据
1
2
3
4
|
<?php
$delete = $db->delete(
"user"
,
"where nikename = #beyondweb#"
);//请把#号替换为单引号
$db->dbClose();
?>
|