现在的位置: 首页 > 综合 > 正文

SqlHelper—基于Mysql扩展库的MySql数据库

2013年12月13日 ⁄ 综合 ⁄ 共 2064字 ⁄ 字号 评论关闭

自己写的一个基于mysql扩展库的SqlHelper类:

 

<?php
	class SqlHelper{
		//VAR
		private $conn;
		private $host;
		private $user;
		private $password;
		private $database;
		
		//Constructor
		function SqlHelper($host, $user, $password, $database) {
			$this->host = $host;
			$this->user = $user;
			$this->password = $password;
			$this->database = $database;
			
			//创建连接
			$this->conn = mysql_connect($this->host, $this->user, $this->password);
			if (!$this->conn){
				die("创建连接失败:".mysql_error());
			}
			//设置数据库编码
			mysql_query("set names utf8", $this->conn);
			//使用一个数据库
			mysql_select_db($this->database, $this->conn) or die("数据库:$this->database不存在!");				
		}
		
		//Object Methods
		
		/**
		 * 执行DQL操作
		 * Enter description here ...
		 * @param unknown_type $sql
		 */
		function execute_dql($sql){
			$res = mysql_query($sql, $this->conn);
			return $res;			
		}
		
		/**
		 * 执行DML操作
		 * 返回:0-->操作失败;1-->操作成功;2-->没有行数影响;
		 * @param unknown_type $sql
		 */
		function execute_dml($sql){
			$res = mysql_query($sql, $this->conn);
			if (!$res){
				return 0;//操作失败
			}
			
			if (mysql_affected_rows($this->conn)>0){
				return 1;//操作成功
			}else{
				return 2;//没有行数影响
			}
		}
		
		/**
		 * 在浏览器显示查询表的所有记录
		 * Enter description here ...
		 * @param unknown_type $tablename
		 */
		function show_table_data($tablename){
			$sql = "select * from $tablename";
			$res = mysql_query($sql, $this->conn);
			if (!$res){
				die("非法查询:".mysql_error());
			}
			//$rows = mysql_affected_rows($this->conn);都可以
			$rows = mysql_num_rows($res);
			$columns = mysql_num_fields($res);
			echo "<table border=1>";
			//打印表头
			echo "<tr>";
			for ($i = 0; $i < $columns; $i++) {
				echo "<th>".mysql_field_name($res, $i)."</th>";
			}
			echo "</tr>";
			
			//打印内容
			while ($row=mysql_fetch_row($res)) {
				echo "<tr>";
				for ($i = 0; $i < $columns; $i++) {
					echo "<td>".$row[$i]."</td>";
				}
				echo "</tr>";
			}
			
			echo "</table>";			
		}
		
		/**
		 * 在浏览器显示查询表的结构
		 * Enter description here ...
		 * @param unknown_type $tablename
		 */
		function show_table_structure($tablename){
			$sql = "desc $tablename";
			$res = mysql_query($sql, $this->conn);
			if (!$res){
				die("非法查询:".mysql_error());
			}
			//$rows = mysql_affected_rows($this->conn);都可以
			$rows = mysql_num_rows($res);
			$columns = mysql_num_fields($res);
			echo "<table border=1>";
			//打印表头
			echo "<tr>";
			for ($i = 0; $i < $columns; $i++) {
				echo "<th>".mysql_field_name($res, $i)."</th>";
			}
			echo "</tr>";
			
			//打印内容
			while ($row=mysql_fetch_row($res)) {
				echo "<tr>";
				for ($i = 0; $i < $columns; $i++) {
					echo "<td>".$row[$i]."</td>";
				}
				echo "</tr>";
			}
			
			echo "</table>";			
		}
	
	}
?>

 

 

【上篇】
【下篇】

抱歉!评论已关闭.