1: <?php
2:
3: /**
4: * MysqliHelper
5: * [面向对象的MysqliHelper的简单封装]
6: */
7: class MysqliHelper
8: {
9: private static $mysqli;
10: private static $host='localhost';
11: private static $uid='root';
12: private static $pwd='1234';
13: private static $dbName='test2';
14:
15: /**
16: * [connect 创建连接]
17: */
18: public static function connect()
19: {
20: if(isset(self::$mysqli))return;
21: self::$mysqli = new MySQLi(self::$host,self::$uid,self::$pwd,self::$dbName);
22: !empty(self::$mysqli) or die("数据库连接失败:".self::$mysqli->connect_error);
23: self::$mysqli->query("set names utf8");
24: }
25:
26: /**
27: * [execute_dml 执行增删改操作]
28: * @param [string] $sql [DML语句]
29: * @return [int] [操作成功返回受影响行数,否则返回-1]
30: */
31: public static function execute_dml($sql)
32: {
33: self::connect();
34: $result = self::$mysqli->query($sql) or die('执行DML语句时出错:'.self::$mysqli->error);
35: if (!$result) {
36: return -1;
37: } else {
38: return self::$mysqli->affected_rows;
39: }
40: }
41:
42: /**
43: * [execute_dql 执行查询操作]
44: * @param [string] $sql [DQL语句]
45: * @return [mysqli_result] [返回查询结果集]
46: */
47: public static function execute_dql($sql)
48: {
49: self::connect();
50: $result = self::$mysqli->query($sql) or die('执行DQL语句时出错:'.self::$mysqli->error);
51: return $result;
52: }
53:
54: /**
55: * [show_table_data 显示表数据]
56: * @param [string] $tableName [表名]
57: * @return [string] [HTML]
58: */
59: public static function show_table_data($tableName)
60: {
61: $result=self::execute_dql("select * from $tableName");
62: //显示表头信息:
63: echo "<br/>数据表:".$result->fetch_field()->table." 总行数:".$result->num_rows;
64: $tableData="<table border='1' cellpadding='5'><tr>";
65: $fieldsCount = $result->field_count;
66: for ($i=0; $i <$fieldsCount; $i++) {
67: $tableData.= "<th>".$result->fetch_field_direct($i)->name."</th>";
68: }
69: $tableData.="</tr>";
70:
71: //显示数据信息:
72: while ($row = $result->fetch_object()) {
73: $tableData.="<tr>";
74: foreach ($row as $value) {
75: $tableData.="<td>$value</td>";
76: }
77: $tableData.="</tr>";
78: }
79: $tableData.="</table>";
80:
81: $result->free();
82: self::$mysqli->close();
83: //或者 mysqli_close(self::$mysqli);
84: echo $tableData;
85: }
86:
87: }
88: ?>