mysql数据库连接操作类

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