php封装操作数据库的类

ConnDB.class.inc.php文件

<?php
// 连接数据库的类
class ConnDB
{
		var $dbtype;
		var $host;
		var $usr;
		var $pwd;
		var $dbname;
		var $conn;
		// 构造方法
		function ConnDB($dbtype,$host,$user,$pwd,$dbname)
		{
				$this->dbtype = $dbtype;
				$this->host = $host;
				$this->pwd = $pwd;
				$this->dbname = $dbname;
				$this->user = $user;
		}
		function GetConn()
		{
			$this->conn = mysql_connect($this->host,$this->user,$this->pwd) or die("数据库服务器连接错误".mysql_error());	
			mysql_select_db($this->dbname,$this->conn) or die("数据库访问错误".mysql_error());
			mysql_query("set names gb2312");// 设置编码格式
			return $this->conn;
		}
		function __destruct()
		{
			$this->CloseDB();	
		}
		function CloseDB()
		{
			mysql_close($this->conn);
		}
		
}
// 数据库操作类
class OperateDB
{
	function Execsql($sql,$conn)
	{
			$sqltype = strtolower(substr(trim($sql),0,6));// 截取sql语句中的前6个字符串,并转换成小写
			$result = mysql_query($sql,$conn);// 执行sql语句
			$calback_arrary = array();// 定义二维数组
			if ("select" == $sqltype)// 判断执行的是select语句
			{
				
				if (false == $result)
				{
					return false;	
				}
				else if (0 == mysql_num_rows($result))
				{
					return false;
				}
				else
				{
					while($result_array = mysql_fetch_array($result))
					{
					array_push($calback_arrary, $result_array);
					}
					return $calback_arrary;// 成功返回查询结果的数组	
				}
			}
			else if ("update" == $sqltype || "insert" == $sqltype || "delete" == $sqltype)
			{
					if ($result)
					{
						return true;
					}
					else
					{
						return false;
					}
			}
	}	
}

?>

// conndb.inc.php文件
<?php
require("ConnDB.class.inc.php");
$ccon = new ConnDB("mysql","localhost","root","root","think_cms");
$operatedb = new OperateDB();
$conn = $ccon->GetConn();

?>

用法:

<?php
require("conndb.inc.php");
$result = $operatedb->Execsql("select * from cms_post where user_id=2",$conn);
foreach($result as $show)
{
	echo $show['post_body'].'<br>';	
}
?>



你可能感兴趣的:(sql,PHP,mysql,数据库,function,数据库服务器)