PHP连接数据库,实现最基本的增删改查(面向对象)
PHP连接数据库,实现最基本的增删改查(面向过程)这篇文章中已经介绍了PHP连接数据库的方法以及最基本的对数据库的操作,但并没有实现模块化,所有的代码全都集中在表现页面中,造成了代码冗余,不仅不利于维护也不利于代码的重用性,那么在这篇文章中将用面向对象的知识对数据库的连接和基本操作方法进行封装,这样就大大避免了代码的重复。
下面我们就来创建一个数据库操作类:
1、创建mysql_class.php文件然后在该文件中创建Mysql类,并定义变量
1 2 3 4 5 6 7 8 9 10 11 |
<?php
class
Mysql{
private
$host;//服务器地址
private
$root;//用户名
private
$password;//密码
private
$database;//数据库名
//后面所提到的各个方法都放在这个类里
//...
}
?>
|
2、通过构造函数初始化类
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()方法,下一步再说
3、创建连接数据库及关闭数据库方法
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);
}
|
4、对mysql_query()、mysql_fetch_array()、mysql_num_rows()函数进行封装
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);
}
|
5、自定义查询数据方法
1 2 3 |
function
select($tableName,$condition){
return
$this->query( "SELECT
* FROM $tableName $condition" );
}
|
6、自定义插入数据方法
1 2 3 |
function
insert($tableName,$fields,$value){
$this->query( "INSERT
INTO $tableName $fields VALUES$value" );
}
|
7、自定义修改数据方法
1 2 3 |
|