这篇文章主要为大家展示了“php如何实现数据库操作类的封装”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“php如何实现数据库操作类的封装”这篇文章吧。
具体内容如下
一、代码
<?php
class ConnDB{
private $local;
private $username;
private $pwd;
private $db;
private $connID;
private $code;
public function __construct($local,$username,$pwd,$connID,$code,$db){
$this->local=$local;
$this->username=$username;
$this->pwd=$pwd;
$this->connID=$connID;
$this->code=$code;
$this->db=$db;
$this->connect();
}
public function connect(){
if($this->connID=="pconn"){
$this->connID=mysql_pconnect($this->local,$this->username,$this->pwd)or die("Connect MySQL False");
}else{
$this->connID=mysql_connect($this->local,$this->username,$this->pwd)or die("Connect MySQL False");
}
mysql_select_db($this->db,$this->connID) or die("Connect DB False");
mysql_query("SET NAMES $this->code");
return $this->connID; //返回数据库连接对象
}
}
class AdminDB{
function executeSQL ($sql, $connID){
$sqlType = strtolower(substr(trim($sql), 0, 6)); //提取SQL语句的类型
$rs = mysql_query($sql,$connID); //执行SQL语句
if ($sqlType == 'select') { //如果是select查询
$arrayData = mysql_fetch_array($rs); //返回查询记录集
if (count($arrayData) == 0 || $rs == false) { //如果没查询到或发生错误
return false; //返回false
} else { //否则
return $arrayData; //返回记录集
}
} elseif ($sqlType == 'insert' || $sqlType == 'update' || $sqlType == 'delete') { //如果执行插入、更新或删除语句
return $rs; //返回语句执行状态,即成功返回true,失败返回false
} else {
return false; //如果不是上述查询,则返回false
}
}
}
$connobj=new ConnDB("localhost","root","root","conn","utf8","db_database20"); //实例化数据库连接类
$conn=$connobj->connect(); //返回连接标识
$admindb=new AdminDB(); //数据库操作类实例化
$res=$admindb->executeSQL ("select * from tb_demo01",$conn); //调用数据库操作类中方法执行查询语句
if($res){ //如果返回结果为真,则输出数据
print_r($res); //输出一个数组。
}
?>
二、运行结果
Array
(
[0] => 1
[id] => 1
[1] => php新书上市
[title] => php新书上市
[2] => php新书上市啦,希望大家给出宝贵意见
[content] => php新书上市啦,希望大家给出宝贵意见
[3] => 2010-10-23
[date] => 2010-10-23
)
以上是“php如何实现数据库操作类的封装”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网行业资讯频道!