下面将PHP数据库的增删改查的操作封装成类,方便直接调用:
0.首先是操作的数据库表的结构:
数据库(数据库名称:db_mxd) 以及表(表名称:userInfo)
1. 数据库链接类ConnDb
<?php /** * 数据库链接类 */ class ConnDB{ var $dbType; //数据库的类型 var $host; //数据库服务器的地址 var $userAccount; //链接数据库帐号 var $userPwd; //链接数据库的密码 var $dbName; //链接的数据库名称 var $conn; //链接数据库的标识符 function ConnDB($_dbType, $_host, $_userAccount, $_userPwd, $_dbName) { $this->dbType = $_dbType; $this->host = $_host; $this->userAccount = $_userAccount; $this->userPwd = $_userPwd; $this->dbName = $_dbName; } function getConnId() { $this->conn = mysql_connect($this->host, $this->userAccount, $this->userPwd) or die('MySQL Connect Info : '.mysql_error()); mysql_select_db($this->dbName, $this->conn) or die('Select DB Error Info : '.mysql_error()); return $this->conn; } function closeConnId() { mysql_close($this->conn); } } ?>
2. 数据库操作类AdminDB
<?php /** * 数据库操作类 */ class AdminDB { // 操作成功,返回由mysql_query()获得的结果集$result // 操作失败,返回false public static function execSQL($sqlStr, $conn) { // 首先截取sql语句的前6个字符串,并转换为小些,判断查询类型 $sqlType = strtolower(substr(trim($sqlStr), 0, 6)); $result = mysql_query($sqlStr, $conn); if($sqlType == "select") { if($result) { return $result; }else{ return false; } }elseif($sqlStr == "update" || $sqlStr == "delete" || $sqlStr == "insert") { if($result) { return true; }else{ return false; } } } } ?>
3.处理结果集的类GetUserInfoUtils
<?php /** * 结果集处理类 */ class GetUserInfoUtils { public static function getUserInfosJSON($result) { $arr = array( 'code'=>'400', 'message'=>'Select Error' ); if($result) { $data = array(); while($obj_result = mysql_fetch_object($result)) { array_push($data, $obj_result); } $arr['code'] = '200'; $arr['message'] = 'Success'; $arr['data'] = $data; }else{ $arr['data'] = null; } return json_encode($arr); } } ?>
<?php require_once "ConnDB.php"; require_once "AdminDB.php"; require_once "GetUserInfoUtils.php"; $connDb = new ConnDB('mysql', '127.0.0.1', 'root', 'root', 'db_mxd'); $conn = $connDb->getConnId(); // 获取数据库链接的标志符 $result = AdminDB::execSQL("select * from userInfo", $conn); // 获取结果集 $data_json = GetUserInfoUtils::getUserInfosJSON($result); echo $data_json; ?>
测试结果:
{
"code": "200",
"message": "Success",
"data": [
{
"id": "1",
"userName": "Tom",
"age": "23",
"resume": "A programer",
"userAccount": "1512547107",
"password": "123456"
},
{
"id": "2",
"userName": "Jake",
"age": "100",
"resume": "NO Data!",
"userAccount": "1234567890",
"password": "111111"
},
{
"id": "3",
"userName": "Green",
"age": "30",
"resume": "NO Data!",
"userAccount": "16255387348",
"password": "6662719"
}
]
}