码迷,mamicode.com
首页 > 数据库 > 详细

PHP数据库操作&分页类

时间:2015-01-24 19:59:55      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

MySQL数据库操作类:

  1 <?php
  2 class mysql {
  3     private $db_host; //数据库主机
  4     private $db_user; //数据库用户名
  5     private $db_pwd; //数据库用户名密码
  6     private $db_database; //数据库名
  7     private $conn; //数据库连接标识;
  8     private $result; //执行query命令的结果资源标识
  9     private $sql; //sql执行语句
 10     private $row; //返回的条目数
 11     private $coding; //数据库编码,GBK,UTF8,gb2312
 12     private $bulletin = true; //是否开启错误记录
 13     private $show_error = true; //测试阶段,显示所有错误,具有安全隐患,默认关闭
 14     private $is_error = false; //发现错误是否立即终止,默认true,建议不启用,因为当有问题时用户什么也看不到是很苦恼的
 15 
 16     /*构造函数*/
 17     public function __construct($db_host, $db_user, $db_pwd, $db_database, $conn, $coding) {
 18         $this->db_host = $db_host;
 19         $this->db_user = $db_user;
 20         $this->db_pwd = $db_pwd;
 21         $this->db_database = $db_database;
 22         $this->conn = $conn;
 23         $this->coding = $coding;
 24         $this->connect();
 25     }
 26 
 27     /*数据库连接*/
 28     public function connect() {
 29         if ($this->conn == "pconn") {
 30             //永久链接
 31             $this->conn = mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd);
 32         } else {
 33             //即使链接
 34             $this->conn = mysql_connect($this->db_host, $this->db_user, $this->db_pwd);
 35         }
 36 
 37         if (!mysql_select_db($this->db_database, $this->conn)) {
 38             if ($this->show_error) {
 39                 $this->show_error("数据库不可用:", $this->db_database);
 40             }
 41         }
 42         mysql_query("SET NAMES $this->coding");
 43     }
 44 
 45     /*数据库执行语句,可执行查询添加修改删除等任何sql语句*/
 46     public function query($sql) {
 47         if ($sql == "") {
 48             $this->show_error("SQL语句错误:", "SQL查询语句为空");
 49         }
 50         $this->sql = $sql;
 51 
 52         $result = mysql_query($this->sql, $this->conn);
 53 
 54         if (!$result) {
 55             //调试中使用,sql语句出错时会自动打印出来
 56             if ($this->show_error) {
 57                 $this->show_error("错误SQL语句:", $this->sql);
 58             }
 59         } else {
 60             $this->result = $result;
 61         }
 62         return $this->result;
 63     }
 64 
 65     /*创建添加新的数据库*/
 66     public function create_database($database_name) {
 67         $database = $database_name;
 68         $sqlDatabase = ‘create database ‘ . $database;
 69         $this->query($sqlDatabase);
 70     }
 71 
 72     /*查询服务器所有数据库*/
 73     //将系统数据库与用户数据库分开,更直观的显示?
 74     public function show_databases() {
 75         $this->query("show databases");
 76         echo "现有数据库:" . $amount = $this->db_num_rows($rs);
 77         echo "<br />";
 78         $i = 1;
 79         while ($row = $this->fetch_array($rs)) {
 80             echo "$i $row[Database]";
 81             echo "<br />";
 82             $i++;
 83         }
 84     }
 85 
 86     //以数组形式返回主机中所有数据库名
 87     public function databases() {
 88         $rsPtr = mysql_list_dbs($this->conn);
 89         $i = 0;
 90         $cnt = mysql_num_rows($rsPtr);
 91         while ($i < $cnt) {
 92             $rs[] = mysql_db_name($rsPtr, $i);
 93             $i++;
 94         }
 95         return $rs;
 96     }
 97 
 98     /*查询数据库下所有的表*/
 99     public function show_tables($database_name) {
100         $this->query("show tables");
101         echo "现有数据库:" . $amount = $this->db_num_rows($rs);
102         echo "<br />";
103         $i = 1;
104         while ($row = $this->fetch_array($rs)) {
105             $columnName = "Tables_in_" . $database_name;
106             echo "$i $row[$columnName]";
107             echo "<br />";
108             $i++;
109         }
110     }
111 
112     /*
113     mysql_fetch_row()    array  $row[0],$row[1],$row[2]
114     mysql_fetch_array()  array  $row[0] 或 $row[id]
115     mysql_fetch_assoc()  array  用$row->content 字段大小写敏感
116     mysql_fetch_object() object 用$row[id],$row[content] 字段大小写敏感
117     */
118 
119     /*取得结果数据*/
120     public function mysql_result_li() {
121         return mysql_result($str);
122     }
123 
124     /*取得记录集,获取数组-索引和关联,使用$row[‘content‘] */
125     public function fetch_array() {
126         return mysql_fetch_array($this->result);
127     }
128 
129     //获取关联数组,使用$row[‘字段名‘]
130     public function fetch_assoc() {
131         return mysql_fetch_assoc($this->result);
132     }
133 
134     //获取数字索引数组,使用$row[0],$row[1],$row[2]
135     public function fetch_row() {
136         return mysql_fetch_row($this->result);
137     }
138 
139     //获取对象数组,使用$row->content
140     public function fetch_Object() {
141         return mysql_fetch_object($this->result);
142     }
143 
144     //简化查询select
145     public function findall($table) {
146         $this->query("SELECT * FROM $table");
147     }
148 
149     //简化查询select
150     public function select($table, $columnName = "*", $condition = ‘‘, $debug = ‘‘) {
151         $condition = $condition ? ‘ Where ‘ . $condition : NULL;
152         if ($debug) {
153             echo "SELECT $columnName FROM $table $condition";
154         } else {
155             $this->query("SELECT $columnName FROM $table $condition");
156         }
157     }
158 
159     //简化删除del
160     public function delete($table, $condition, $url = ‘‘) {
161         if ($this->query("DELETE FROM $table WHERE $condition")) {
162             if (!empty ($url))
163                 $this->Get_admin_msg($url, ‘删除成功!‘);
164         }
165     }
166 
167     //简化插入insert
168     public function insert($table, $columnName, $value, $url = ‘‘) {
169         if ($this->query("INSERT INTO $table ($columnName) VALUES ($value)")) {
170             if (!empty ($url))
171                 $this->Get_admin_msg($url, ‘添加成功!‘);
172         }
173     }
174 
175     //简化修改update
176     public function update($table, $mod_content, $condition, $url = ‘‘) {
177         //echo "UPDATE $table SET $mod_content WHERE $condition"; exit();
178         if ($this->query("UPDATE $table SET $mod_content WHERE $condition")) {
179             if (!empty ($url))
180                 $this->Get_admin_msg($url);
181         }
182     }
183 
184     /*取得上一步 INSERT 操作产生的 ID*/
185     public function insert_id() {
186         return mysql_insert_id();
187     }
188 
189     //指向确定的一条数据记录
190     public function db_data_seek($id) {
191         if ($id > 0) {
192             $id = $id -1;
193         }
194         if (!@ mysql_data_seek($this->result, $id)) {
195             $this->show_error("SQL语句有误:", "指定的数据为空");
196         }
197         return $this->result;
198     }
199 
200     // 根据select查询结果计算结果集条数
201     public function db_num_rows() {
202         if ($this->result == null) {
203             if ($this->show_error) {
204                 $this->show_error("SQL语句错误", "暂时为空,没有任何内容!");
205             }
206         } else {
207             return mysql_num_rows($this->result);
208         }
209     }
210 
211     // 根据insert,update,delete执行结果取得影响行数
212     public function db_affected_rows() {
213         return mysql_affected_rows();
214     }
215 
216     //输出显示sql语句
217     public function show_error($message = "", $sql = "") {
218         if (!$sql) {
219             echo "<font color=‘red‘>" . $message . "</font>";
220             echo "<br />";
221         } else {
222             echo "<fieldset>";
223             echo "<legend>错误信息提示:</legend><br />";
224             echo "<div style=‘font-size:14px; clear:both; font-family:Verdana, Arial, Helvetica, sans-serif;‘>";
225             echo "<div style=‘height:20px; background:#000000; border:1px #000000 solid‘>";
226             echo "<font color=‘white‘>错误号:12142</font>";
227             echo "</div><br />";
228             echo "错误原因:" . mysql_error() . "<br /><br />";
229             echo "<div style=‘height:20px; background:#FF0000; border:1px #FF0000 solid‘>";
230             echo "<font color=‘white‘>" . $message . "</font>";
231             echo "</div>";
232             echo "<font color=‘red‘><pre>" . $sql . "</pre></font>";
233             $ip = $this->getip();
234             if ($this->bulletin) {
235                 $time = date("Y-m-d H:i:s");
236                 $message = $message . "/r/n$this->sql" . "/r/n客户IP:$ip" . "/r/n时间 :$time" . "/r/n/r/n";
237 
238                 $server_date = date("Y-m-d");
239                 $filename = $server_date . ".txt";
240                 $file_path = "error/" . $filename;
241                 $error_content = $message;
242                 //$error_content="错误的数据库,不可以链接";
243                 $file = "error"; //设置文件保存目录
244 
245                 //建立文件夹
246                 if (!file_exists($file)) {
247                     if (!mkdir($file, 0777)) {
248                         //默认的 mode 是 0777,意味着最大可能的访问权
249                         die("upload files directory does not exist and creation failed");
250                     }
251                 }
252 
253                 //建立txt日期文件
254                 if (!file_exists($file_path)) {
255 
256                     //echo "建立日期文件";
257                     fopen($file_path, "w+");
258 
259                     //首先要确定文件存在并且可写
260                     if (is_writable($file_path)) {
261                         //使用添加模式打开$filename,文件指针将会在文件的开头
262                         if (!$handle = fopen($file_path, ‘a‘)) {
263                             echo "不能打开文件 $filename";
264                             exit;
265                         }
266 
267                         //将$somecontent写入到我们打开的文件中。
268                         if (!fwrite($handle, $error_content)) {
269                             echo "不能写入到文件 $filename";
270                             exit;
271                         }
272 
273                         //echo "文件 $filename 写入成功";
274 
275                         echo "——错误记录被保存!";
276 
277                         //关闭文件
278                         fclose($handle);
279                     } else {
280                         echo "文件 $filename 不可写";
281                     }
282 
283                 } else {
284                     //首先要确定文件存在并且可写
285                     if (is_writable($file_path)) {
286                         //使用添加模式打开$filename,文件指针将会在文件的开头
287                         if (!$handle = fopen($file_path, ‘a‘)) {
288                             echo "不能打开文件 $filename";
289                             exit;
290                         }
291 
292                         //将$somecontent写入到我们打开的文件中。
293                         if (!fwrite($handle, $error_content)) {
294                             echo "不能写入到文件 $filename";
295                             exit;
296                         }
297 
298                         //echo "文件 $filename 写入成功";
299                         echo "——错误记录被保存!";
300 
301                         //关闭文件
302                         fclose($handle);
303                     } else {
304                         echo "文件 $filename 不可写";
305                     }
306                 }
307 
308             }
309             echo "<br />";
310             if ($this->is_error) {
311                 exit;
312             }
313         }
314         echo "</div>";
315         echo "</fieldset>";
316 
317         echo "<br />";
318     }
319 
320     //释放结果集
321     public function free() {
322         @ mysql_free_result($this->result);
323     }
324 
325     //数据库选择
326     public function select_db($db_database) {
327         return mysql_select_db($db_database);
328     }
329 
330     //查询字段数量
331     public function num_fields($table_name) {
332         //return mysql_num_fields($this->result);
333         $this->query("select * from $table_name");
334         echo "<br />";
335         echo "字段数:" . $total = mysql_num_fields($this->result);
336         echo "<pre>";
337         for ($i = 0; $i < $total; $i++) {
338             print_r(mysql_fetch_field($this->result, $i));
339         }
340         echo "</pre>";
341         echo "<br />";
342     }
343 
344     //取得 MySQL 服务器信息
345     public function mysql_server($num = ‘‘) {
346         switch ($num) {
347             case 1 :
348                 return mysql_get_server_info(); //MySQL 服务器信息
349                 break;
350 
351             case 2 :
352                 return mysql_get_host_info(); //取得 MySQL 主机信息
353                 break;
354 
355             case 3 :
356                 return mysql_get_client_info(); //取得 MySQL 客户端信息
357                 break;
358 
359             case 4 :
360                 return mysql_get_proto_info(); //取得 MySQL 协议信息
361                 break;
362 
363             default :
364                 return mysql_get_client_info(); //默认取得mysql版本信息
365         }
366     }
367 
368     //析构函数,自动关闭数据库,垃圾回收机制
369     public function __destruct() {
370         if (!empty ($this->result)) {
371             $this->free();
372         }
373         mysql_close($this->conn);
374     } //function __destruct();
375 
376     /*获得客户端真实的IP地址*/
377     function getip() {
378         if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
379             $ip = getenv("HTTP_CLIENT_IP");
380         } else
381             if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
382                 $ip = getenv("HTTP_X_FORWARDED_FOR");
383             } else
384                 if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
385                     $ip = getenv("REMOTE_ADDR");
386                 } else
387                     if (isset ($_SERVER[‘REMOTE_ADDR‘]) && $_SERVER[‘REMOTE_ADDR‘] && strcasecmp($_SERVER[‘REMOTE_ADDR‘], "unknown")) {
388                         $ip = $_SERVER[‘REMOTE_ADDR‘];
389                     } else {
390                         $ip = "unknown";
391                     }
392         return ($ip);
393     }
394     function inject_check($sql_str) { //防止注入
395         $check = eregi(‘select|insert|update|delete|/‘|///*|/*|/././/|/.//|union|into|load_file|outfile‘, $sql_str);
396         if ($check) {
397             echo "输入非法注入内容!";
398             exit ();
399         } else {
400             return $sql_str;
401         }
402     }
403     function checkurl() { //检查来路
404         if (preg_replace("/https?:////([^/://]+).*/i", "//1", $_SERVER[‘HTTP_REFERER‘]) !== preg_replace("/([^/:]+).*/", "//1", $_SERVER[‘HTTP_HOST‘])) {
405             header("Location: http://www.kebeke.com");
406             exit();
407         }
408     }
409 
410 }
411 ?>

 分页类

 1 <?php
 2 /*
 3  * Created on 2007-6-8
 4  * Programmer : Alan , Msn - haowubai@hotmail.com
 5  * php100.com Develop a project PHP - MySQL - Apache
 6  * Window - Preferences - PHPeclipse - PHP - Code Templates
 7  */
 8 //为了避免重复包含文件而造成错误,加了判断函数是否存在的条件:
 9 $page = $_GET[page];
10 if(!function_exists(pageft)){
11 //定义函数pageft(),三个参数的含义为:
12 //$totle:信息总数;
13 //$displaypg:每页显示信息数,这里设置为默认是20;
14 //$url:分页导航中的链接,除了加入不同的查询信息“page”外的部分都与这个URL相同。
15 //   默认值本该设为本页URL(即$_SERVER["REQUEST_URI"]),但设置默认值的右边只能为常量,所以该默认值设为空字符串,在函数内部再设置为本页URL。
16 function pageft($totle,$displaypg=20,$url=‘‘){
17 
18     //定义几个全局变量:
19     //$page:当前页码;
20     //$firstcount:(数据库)查询的起始项;
21     //$pagenav:页面导航条代码,函数内部并没有将它输出;
22     //$_SERVER:读取本页URL“$_SERVER["REQUEST_URI"]”所必须。
23     global $page,$firstcount,$pagenav,$_SERVER;
24     
25     //为使函数外部可以访问这里的“$displaypg”,将它也设为全局变量。注意一个变量重新定义为全局变量后,原值被覆盖,所以这里给它重新赋值。
26     $GLOBALS["displaypg"]=$displaypg;
27     
28     if(!$page) $page=1;
29     
30     //如果$url使用默认,即空值,则赋值为本页URL:
31     if(!$url){ $url=$_SERVER["REQUEST_URI"];}
32     
33     //URL分析:
34     $parse_url=parse_url($url);
35     $url_query=$parse_url["query"]; //单独取出URL的查询字串
36     if($url_query){
37     //因为URL中可能包含了页码信息,我们要把它去掉,以便加入新的页码信息。
38     //这里用到了正则表达式,请参考“PHP中的正规表达式”
39     $url_query=ereg_replace("(^|&)page=$page","",$url_query);
40     
41     //将处理后的URL的查询字串替换原来的URL的查询字串:
42     $url=str_replace($parse_url["query"],$url_query,$url);
43     
44     //在URL后加page查询信息,但待赋值:
45     if($url_query) $url.="&page"; else $url.="page";
46     }else {
47     $url.="?page";
48     }
49     
50     //页码计算:
51     $lastpg=ceil($totle/$displaypg); //最后页,也是总页数
52     $page=min($lastpg,$page);
53     $prepg=$page-1; //上一页
54     $nextpg=($page==$lastpg ? 0 : $page+1); //下一页
55     $firstcount=($page-1)*$displaypg;
56     
57     //开始分页导航条代码:
58     $pagenav="显示第 <B>".($totle?($firstcount+1):0)."</B>-<B>".min($firstcount+$displaypg,$totle)."</B> 条记录,共 $totle 条记录";
59     
60     //如果只有一页则跳出函数:
61     if($lastpg<=1) return false;
62     
63     $pagenav.=" <a href="$url=1" mce_href="$url=1">首页</a> ";
64     if($prepg) $pagenav.=" <a href="$url=$prepg" mce_href="$url=$prepg">前页</a> "; else $pagenav.=" 前页 ";
65     if($nextpg) $pagenav.=" <a href="$url=$nextpg" mce_href="$url=$nextpg">后页</a> "; else $pagenav.=" 后页 ";
66     $pagenav.=" <a href="$url=$lastpg" mce_href="$url=$lastpg">尾页</a> ";
67     
68     //下拉跳转列表,循环列出所有页码:
69     $pagenav.=" 到第 <select name=‘topage‘ size=‘1‘ onchange=‘window.location=/"$url=/"+this.value‘>/n";
70     for($i=1;$i<=$lastpg;$i++){
71         if($i==$page) $pagenav.="<option value=‘$i‘ selected>$i</option>/n";
72         else $pagenav.="<option value=‘$i‘>$i</option>/n";    
73     }
74     $pagenav.="</select> 页,共 $lastpg 页";
75 }
76 }
77 ?>

 

PHP数据库操作&分页类

标签:

原文地址:http://www.cnblogs.com/miencun/p/4246336.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!