1: <?php
2:
3: /**
4: * Mysql数据帮助类
5: */
6: class MysqlHelper
7: {
8: function __construct()
9: {
10: if(isset($conn)){return;}
11: //创建连接对象
12: $this->conn=@mysql_connect($this->host,$this->uid,$this->pwd);
13: if(!$this->conn){
14: die('连接数据库失败:'.mysql_error());
15: }
16:
17: //选择数据库和设置编码
18: mysql_select_db($this->db,$this->conn);
19: mysql_query('set names utf8');
20: }
21:
22: private $conn;
23: private $host='localhost';
24: private $uid='root';
25: private $pwd='1234';
26: private $db='test2';
27:
28: /**
29: * [execute_dql 执行查询语句]
30: * @param [string] $sql [查询语句]
31: */
32: public function execute_dql($sql)
33: {
34: $result = mysql_query($sql,$this->conn) or die('执行DQL语句时出错:'.mysql_error());
35: return $result;
36: }
37:
38: /**
39: * [execute_dml 执行增删改语句]
40: * @param [string] $sql [查询语句]
41: * @return [失败返回-1,无影响返回0,成功返回受影响的行数]
42: */
43: public function execute_dml($sql)
44: {
45: $result = mysql_query($sql,$this->conn) or die('执行DML语句时出错:'.mysql_error());
46: if(!$result){
47: return -1; //操作失败
48: }else{
49: return mysql_affected_rows($this->conn);
50: }
51: }
52:
53: /**
54: * [show_table_data 显示表数据]
55: * @param [string] $tableName [表名]
56: * @return [string] [HTML表格]
57: */
58: public function show_table_data($tableName)
59: {
60: $result = $this->execute_dql("select * from $tableName");
61:
62: $this->show_table($result);
63:
64: mysql_free_result($result);
65: mysql_close($this->conn);
66: }
67:
68: /**
69: * [show_table_info 显示表结构]
70: * @param [string] $tableName [表名]
71: * @return [string] [HTML表格]
72: */
73: public function show_table_info($tableName)
74: {
75: $result = $this->execute_dql("desc $tableName");
76:
77: $this->show_table($result);
78:
79: mysql_free_result($result);
80: mysql_close($this->conn);
81: }
82:
83: /**
84: * [show_table 拼接表格]
85: * @param [resource] $result [结果集]
86: * @return [string] [HTML]
87: */
88: public function show_table($result)
89: {
90: //显示表头信息:
91: echo "<br/>数据表:".mysql_field_table($result, 0)." 总行数:".mysql_num_rows($result);
92: $tableData="<table border='1' cellpadding='5'><tr>";
93: $fieldsCount = mysql_num_fields($result);
94: for ($i=0; $i <$fieldsCount; $i++) {
95: $tableData.= "<th>".mysql_field_name($result, $i)."</th>";
96: }
97: $tableData.="</tr>";
98:
99: //显示数据信息:
100: while ($row = mysql_fetch_object($result)) {
101: $tableData.="<tr>";
102: foreach ($row as $value) {
103: $tableData.="<td>$value</td>";
104: }
105: $tableData.="</tr>";
106: }
107: $tableData.="</table>";
108:
109: echo $tableData;
110: }
111: }
112:
113: ?>