PHP实现的mysql操作类【MySQL与MySQLi方式】

这篇文章主要介绍了PHP实现的mysql操作类,结合实例形式分析了MySQL与MySQLi方式连接与操作MySQL数据库的常用方法封装与使用技巧,需要的朋友可以参考下

本文实例讲述了PHP实现的mysql操作类,分享给大家供大家参考,具体如下:

首先是mysql方式

  1. <?php
  2. class ConnectionMySQL{
  3. //主机
  4. private $host="localhost";
  5. //数据库的username
  6. private $name="root";
  7. //数据库的password
  8. private $pass="";
  9. //数据库名称
  10. private $table="phptest";
  11. //编码形式
  12. private $ut="utf-8";
  13. //构造函数
  14. function __construct(){
  15. $this->ut=$ut;
  16. $this->connect();
  17. }
  18. //数据库的链接
  19. function connect(){
  20. $link=mysql_connect($this->host,$this->name,$this->pass) or die ($this->error());
  21. mysql_select_db($this->table,$link) or die("没该数据库:".$this->table);
  22. mysql_query("SET NAMES '$this->ut'");
  23. }
  24. function query($sql, $type = '') {
  25. if(!($query = mysql_query($sql))) $this->show('Say:', $sql);
  26. return $query;
  27. }
  28. function show($message = '', $sql = '') {
  29. if(!$sql) echo $message;
  30. else echo $message.'<br>'.$sql;
  31. }
  32. function affected_rows() {
  33. return mysql_affected_rows();
  34. }
  35. function result($query, $row) {
  36. return mysql_result($query, $row);
  37. }
  38. function num_rows($query) {
  39. return @mysql_num_rows($query);
  40. }
  41. function num_fields($query) {
  42. return mysql_num_fields($query);
  43. }
  44. function free_result($query) {
  45. return mysql_free_result($query);
  46. }
  47. function insert_id() {
  48. return mysql_insert_id();
  49. }
  50. function fetch_row($query) {
  51. return mysql_fetch_row($query);
  52. }
  53. function version() {
  54. return mysql_get_server_info();
  55. }
  56. function close() {
  57. return mysql_close();
  58. }
  59. //向$table表中插入值
  60. function fn_insert($table,$name,$value){
  61. $this->query("insert into $table ($name) value ($value)");
  62. }
  63. //根据$id值删除表$table中的一条记录
  64. function fn_delete($table,$id,$value){
  65. $this->query("delete from $table where $);
  66. echo "id为". $id." 的记录被成功删除!";
  67. }
  68. }
  69. $db = new ConnectionMySQL();
  70. $db->fn_insert('test','id,name,sex',"'','hongtenzone','M'");
  71. $db->fn_delete('test', 'id', 1);
  72. ?>

mysqli的方式:

  1. <?php
  2. class Mysql{
  3. private $LocalHost = 'localhost';
  4. private $LoaclUser = '';
  5. private $LocalPass = '';
  6. private $LocalBase = '';
  7. private $LocalCode = 'UTF8';
  8. private $PreFix;
  9. private $Conn;
  10. private $Start = 0;
  11. private $Error = false; //数据库连接状态, false表示未连接或连接不正常
  12. public $Err = true; //Sql执行结果
  13. private $Table;
  14. private $Field = '*';
  15. private $Where = '';
  16. private $Order = '';
  17. private $PageSize = 0; //分页显示->每页多少条,0为不分页显示
  18. private $PageCount = 1; //分页显示->总共有多少条
  19. private $PageNum = 1; //分页显示->总共有多少页
  20. private $PageNo = 1; //分页显示->当前第几页
  21. private $PageKey = 'page'; //分页url参数键
  22. private $PageStart = 0; //分页显示->当前从第几条开始返回
  23. private $Select;
  24. private $Rest;
  25. private $Result = false;//结果集
  26. public $FormArray = array();
  27. public $Instr_ID = 0;
  28. private $j = 0;
  29. public function Parameter($Loca, $Root, $Pass, $Base, $Code, $PreFix = ''){
  30. $this->LoaclUser = $Root;
  31. $this->LocalBase = $Base;
  32. $this->LocalCode = $Code;
  33. $this->LocalHost = $Loca;
  34. $this->LocalPass = $Pass;
  35. $this->PreFix = $PreFix;
  36. return $this;
  37. }
  38. private function Connection( $Sql ){
  39. !function_exists(mysqli_connect) ? die('查询失败,无法加载mysqli扩展') : null;
  40. $this->Conn = @new mysqli( $this->LocalHost, $this->LoaclUser, $this->LocalPass, $this->LocalBase);
  41. $this->Error = mysqli_connect_errno() == 0 ? true : false;
  42. !$this->Error ? die('数据库连接错误,请检查数据库连接参数') : null;
  43. $this->Conn->query('SET NAMES ' . $this->LocalCode);
  44. $this->Rest = $this->Conn->query($Sql);
  45. $this->Err = mysqli_error($this->Conn);
  46. $this->Instr_ID = mysqli_insert_id($this->Conn);
  47. $this->Rest->free_result;
  48. $this->Conn->close;
  49. $this -> FormArray = '';
  50. return $this;
  51. }
  52. public function null(){
  53. $this->PageSize = 0;
  54. //$this->PageCount = 1;
  55. $this->PageStart = 1;
  56. $this->Field = ' * ';
  57. $this->Select = '';
  58. unset($this->Table, $this->Where,$this->Order, $this->Result);
  59. }
  60. public function Table( $TableName ) {//数据表
  61. $this -> null();
  62. $this->Table = '`' . $this->PreFix . $TableName . '`';
  63. return $this;
  64. }
  65. public function Field( $Array = '*' ) {//数据字段
  66. !emptyempty( $this->Field ) ? $this->Field = '' : null;
  67. $Array = explode(',', $Array);
  68. foreach ( $Array as $field ) {
  69. $this->Field .= !$this->Start ? '`' . $field . '`' : ', `' . $field . '`';
  70. $this->Start++;
  71. }
  72. $this->Start = 0;
  73. return $this;
  74. }
  75. public function Where( $Where ) {//条件
  76. $this->Where = ' where ' .$Where;
  77. return $this;
  78. }
  79. public function Order( $Order ) {//排序
  80. $this->Order = ' order by ' . $Order;
  81. return $this;
  82. }
  83. public function pk( $key ) {//分页url参数键
  84. $this->PageKey = $key;
  85. return $this;
  86. }
  87. public function Page( $PageSize ) {//分页
  88. $this->PageSize = $PageSize;
  89. $this->PageNo = $this->get( $this->PageKey );
  90. $this->PageNo = emptyempty( $this->PageNo ) || !isset( $this->PageNo ) || !is_numeric( $this->PageNo ) || $this->PageNo < 1 ? 1 : $this->PageNo;
  91. return $this;
  92. }
  93. public function post( $Key, $Filter = true ){
  94. return $Filter ? strip_tags($_POST[$Key]) : $_POST[$Key];
  95. }
  96. public function get( $Key, $Filter = true ){
  97. return $Filter ? strip_tags($_GET[$Key]) : $_GET[$Key];
  98. }
  99. public function Sel(){
  100. $this->Select = 'Select ' . $this->Field . ' from ' . $this->Table . $this->Where . $this->Order;
  101. $this->Connection( $this->Select );
  102. if ( $this->Rest->num_rows ) {
  103. while ( $Rs = $this->Rest->fetch_assoc() ) {
  104. $this->Result[] = $Rs;
  105. }
  106. }
  107. $DataBase = $this->Result;
  108. return emptyempty($DataBase) ? false : $DataBase;
  109. }
  110. public function querys( $Sql = '', $Type = 'not', $biao = false ) {
  111. $this->Select = $Sql;
  112. $this->Connection( $this->Select );
  113. if ( $this->Rest->num_rows ) {
  114. if ( !$biao ) {
  115. while ( $Rs = $this->Rest->fetch_array() ) {
  116. $this->Result[] = !preg_match('/^\d+$/i', $Type) ? $Rs : $Rs[ $Type ];
  117. }
  118. } else {
  119. while ( $Rs = $this->Rest->fetch_assoc() ) {
  120. $this->Result[] = $Rs;
  121. }
  122. }
  123. }
  124. $DataBase = $this->Result;
  125. return emptyempty($DataBase) ? false : $DataBase;
  126. }
  127. public function executes( $Sql = '' ){
  128. $this->Connection( $Sql );
  129. return $this->Rest;
  130. }
  131. public function exists( $T = '', $F = '', $W = ''){
  132. if ( emptyempty( $F ) ) { return 0; }
  133. $cmd = emptyempty( $W ) ? 'Select sum(' . $F . ') as `baiyinum` from `' . $this->PreFix . $T .'`' : 'Select sum(' . $F . ') as `baiyinum` from `' . $this->PreFix . $T .'` Where ' . $W;
  134. $this->Connection( $cmd );
  135. unset( $T, $F, $W, $cmd );
  136. $Rel = $this->Rest->fetch_array();
  137. return round( $Rel['baiyinum'], 2 );
  138. }
  139. public function ExistsTo( $Bili = 10000, $T = '', $F = '', $W = ''){
  140. if ( emptyempty( $F ) ) { return 0; }
  141. $cmd = emptyempty( $W ) ? 'Select sum(' . $F . ') as `baiyinum` from `' . $this->PreFix . $T .'`' : 'Select sum(' . $F . ') as `baiyinum` from `' . $this->PreFix . $T .'` Where ' . $W;
  142. $this->Connection( $cmd );
  143. unset( $T, $F, $W, $cmd );
  144. $Rel = $this->Rest->fetch_array();
  145. return round( $Rel['baiyinum'] * $Bili );
  146. }
  147. public function Select( $Type = true, $ListNum = 1 ){ //返回记录(数组形式, 返回条数)
  148. $this->Select = 'Select ' . $this->Field . ' from ' . $this->Table . $this->Where . $this->Order;
  149. if ( is_numeric( $ListNum ) ) {
  150. if ( $this->PageSize > 0 ) {
  151. $this->Connection( $this->Select );//执行查询
  152. $this->PageCount = $this->Rest->num_rows;//取得记录总数
  153. $this->PageNum = ceil($this->PageCount / $this->PageSize); //总共有多少页
  154. $this->PageNo = $this->PageNo > $this->PageNum ? $this->PageNum : $this->PageNo;
  155. $this->PageStart = ( $this->PageNo - 1 ) * $this->PageSize; //当前从第几条开始返回
  156. $this->Select .= ' limit ' . $this->PageStart . ', ' .$this->PageSize; //重新构造sql语句
  157. } else {
  158. $this->Select .= ' limit ' . $ListNum; //重新构造sql语句
  159. }
  160. } else {
  161. $this->Select .= ' limit 1'; //重新构造sql语句
  162. }
  163. //echo $this->Select;
  164. $this->Connection( $this->Select );//再次执行查询
  165. if ( $this->Rest->num_rows ) {//如果记录存在
  166. if ( $Type ) {
  167. while ( $Rs = $this->Rest->fetch_array() ) {
  168. $this->Result[] = $Rs;
  169. }
  170. }else{
  171. while ( $Rs = $this->Rest->fetch_assoc() ) {
  172. $this->Result[] = $Rs;
  173. }
  174. }
  175. }
  176. if ( ( $ListNum == 1 or !is_numeric( $ListNum ) ) && !$this->PageSize) { $this->Result = $this->Result[0]; }
  177. $DataBase = $this->Result;
  178. return emptyempty($DataBase) ? false : $DataBase;
  179. }
  180. public function Num() { //返回记录总数
  181. $this->Select = 'Select ' . $this->Field . ' from ' . $this->Table . $this->Where . $this->Order;
  182. $this->Connection( $this->Select );//执行查询
  183. return $this->Rest->num_rows;//取得记录总数
  184. }
  185. public function PageNav($NumNav = false ) { //分页
  186. $Action = $this -> get('action');
  187. !emptyempty( $Action ) or $Action = 'index';
  188. $Module = $this -> get('module');
  189. !emptyempty( $Module ) or $Module = 'index';
  190. $NavUrl = '/' . $Module . '/' . $Action . '/' . $this -> PageKey .'/';
  191. $NaIndex = '/' . $Module . '/' . $Action;
  192. $PageHtml = "\n<div class=\"pagenav\">";
  193. $PageHtml .= '<span>' . $this->PageCount . '条记录 ' . $this->PageNo . '/' . $this->PageNum . '页</span> ';
  194. $this->PageNo <= 1 or $PageHtml .= "<a href=\"" . $NaIndex . "\">首页</a>\n<a href=\"" . $NavUrl . ($this->PageNo - 1) . "\">上一页</a>\n";
  195. if ( $NumNav ) { $PageHtml .= $this->NumPage($NavUrl); }
  196. $this->PageNo >= $this->PageNum or $PageHtml .= "<a href=\"" . $NavUrl. ($this->PageNo + 1) . "\">下一页</a>\n<a href=\"" . $NavUrl . $this->PageNum . "\">尾页</a>\n";
  197. $PageHtml .= "</div>\n";
  198. return $PageHtml;
  199. }
  200. private function NumPage( $Can = '' ) { //数字分页
  201. $NumHtml = '';
  202. $First = 1;
  203. $Last = $this->PageNum;
  204. if ( $this->PageNum > 5 ) {
  205. if ( $this->PageNo < $this->PageNum ) {
  206. $First = $this->PageNo - 2;
  207. $Last = $this->PageNo + 2;
  208. }else{
  209. $First = $this->PageNo - 4;
  210. $Last = $this->PageNum;
  211. }
  212. }
  213. if ( $First < 1 ) { $First = 1; $Last = $First + 4;}
  214. if ( $Last > $this->PageNum ) { $First = $this->PageNum - 4; $Last = $this->PageNum;}
  215. for( $i = $First; $i <= $Last; $i++) {
  216. $NumHtml .= $this->PageNo != $i ? "\n\t" . '<a href="' . $Can . $i . '" rel="external nofollow" >' . $i . '</a>' . "\n\t" : "\n\t" .'<a class="hover" disabled="disabled">' . $i . '</a>' . "\n\t";
  217. }
  218. unset($Can, $First, $i, $Last);
  219. return $NumHtml;
  220. }
  221. public function UserPage($NumNav = false, $PageName = 'index', $Mulu = 'user' ) { //会员中心分页
  222. $NavUrl = '/' . $Mulu . '/' . $PageName . '/' . $this->PageKey . '/';
  223. $PageHtml = "\n<div class=\"pagenav\">";
  224. $PageHtml .= '<span>' . $this->PageCount . '条记录 ' . $this->PageNo . '/' . $this->PageNum . '页</span> ';
  225. $this->PageNo <= 1 or $PageHtml .= "<a href=\"" . $NavUrl . "1\">首页</a>\n<a href=\"" . $NavUrl . ($this->PageNo - 1) . "\">上一页</a>\n";
  226. if ( $NumNav ) { $PageHtml .= $this->NumPage($NavUrl); }
  227. $this->PageNo >= $this->PageNum or $PageHtml .= "<a href=\"" . $NavUrl. ($this->PageNo + 1) . "\">下一页</a>\n<a href=\"" . $NavUrl . $this->PageNum . "\">尾页</a>\n";
  228. $PageHtml .= "</div><div class=\"clear\"></div>\n";
  229. return $PageHtml;
  230. }
  231. //表单处理开始
  232. //判断表单时候提交
  233. public function FormIs( $Keys = 'mm' ) {
  234. return $_POST[ $Keys ] == 1 ? true : false;
  235. }
  236. //post方式获取数据
  237. public function _post( $Keys = '', $TiHuan = '') {
  238. $Values = strip_tags( $_POST[ $Keys ] );
  239. $this->FormArray[$Keys] = emptyempty( $Values ) ? $TiHuan : $Values;
  240. return emptyempty( $Values ) ? $TiHuan : $Values;
  241. }
  242. //get方法获取数据
  243. public function _get( $Keys = '', $TiHuan = '') {
  244. $Values = strip_tags( $_GET[ $Keys ] );
  245. return emptyempty( $Values ) ? $TiHuan : $Values;
  246. }
  247. //判断是否为数字并且不小于0
  248. public function IsNum( $Num = 0, $Mesg = '参数必须为数字' ) {
  249. if ( is_numeric( $Num ) && !emptyempty( $Num ) && $Num >= 0 ) {
  250. return $Num;
  251. }else{
  252. die( $Mesg );
  253. }
  254. }
  255. //判断是否为数字并且不小于0返回True/False
  256. public function NumBer( $Num = 0) {
  257. return is_numeric( $Num ) && !emptyempty( $Num ) && $Num >= 0 ? true : false;
  258. }
  259. //检测相关数据似乎存在
  260. public function IsData($Types = true, $memg = '数据已经存在' ){
  261. $this->Connection('select ' . $this->Field . ' from ' . $this->Table . $this->Where);
  262. if ( $Types ){
  263. $this->Rest->num_rows > 0 ? die( $memg ) : null;
  264. } else {
  265. return $this->Rest->num_rows;
  266. }
  267. }
  268. //写入数据库记录
  269. public function into( $Mesg = '' ){
  270. !is_array( $this->FormArray ) ? die( $Mesg ) : null;
  271. $Sql = 'insert into ' . $this->Table . ' (`';
  272. $I = 0;
  273. foreach ( $this->FormArray as $Key => $Val ){
  274. $Duan .= !$I ? $Key . '`' : ', `' . $Key . '`';
  275. if ( is_numeric( $Val ) ){
  276. $Vals .= !$I ? $Val : ', ' . $Val;
  277. }else{
  278. $Vals .= !$I ? '\'' . $Val . '\'' : ', \'' . $Val . '\'';
  279. }
  280. $I++;
  281. }
  282. $Sql .= $Duan . ') values (' . $Vals . ')';
  283. //@file_put_contents('1.sql', $Sql, FILE_APPEND);
  284. $this->Connection( $Sql );
  285. return !emptyempty( $this->Err ) ? false : true;
  286. }
  287. //数组形式写入数据
  288. public function MsgBox( $Table = '', $Filed = array() ) {
  289. $this -> Table($Table);
  290. foreach( $Filed as $Key => $Val ) {
  291. $this -> FormArray[ $Key ] = $Val;
  292. }
  293. return $this -> Into('未取得数据');
  294. }
  295. //修改数据库记录
  296. public function Edit( $Array = array() ) {
  297. if ( emptyempty( $Array ) ) { $Array = $this -> FormArray; }
  298. if ( !is_array( $Array ) || emptyempty( $Array ) ) {
  299. return false;
  300. } else {
  301. $Sql = 'update ' . $this -> Table . ' set ';
  302. $I = 0;
  303. $Sub = '';
  304. $Huan = array('-' => '[jian]', '+' => '[jia]', '*' => '[cheng]', '/' => '[chu]');
  305. $Zhan = array('[jian]' => '-', '[jia]' => '+', '[cheng]' => '*', '[chu]' => '/');
  306. foreach ( $Array as $Files => $Val ) {
  307. $Val = !is_numeric( $Val ) && !preg_match('/\`\w+\`\s*(\+|\-|\*|\/)/i', $Val) ? '\'' . $Val . '\'' : $Val;
  308. foreach ( $Huan as $key => $val ){
  309. $Val = str_replace($key, $val, $Val);
  310. }
  311. $duan = !$I ? '`' . $Files . '` = ' : ', `' . $Files . '` = ';
  312. $Sub .= $duan . $Val;
  313. $I++;
  314. }
  315. $Sql .= $Sub . $this -> Where;
  316. foreach ( $Zhan as $Fan => $Hui ) {
  317. $Sql = str_replace($Fan, $Hui, $Sql);
  318. }
  319. //echo $Sql; die;
  320. $this -> Connection( $Sql );
  321. unset( $Array, $duan, $Fan, $Files, $Huan, $Hui, $I, $key, $Sql, $Sub, $Val, $Zhan, $val );
  322. return !emptyempty( $this -> Err ) ? false : true;
  323. }
  324. }
  325. //删除数据库记录
  326. public function del(){
  327. $Sql = 'delete from ' . $this->Table . $this->Where;
  328. $this->Connection( $Sql );
  329. unset($Sql);
  330. return !emptyempty( $this->Err ) ? false : true;
  331. }
  332. //表单处理结束
  333. //页面跳转
  334. public function Msg( $Text = '操作成功' ) {
  335. echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  336. echo '<script type="text/javascript">
  337. <!--
  338. alert("' . $Text . '");
  339. document.location="' . $_SERVER['HTTP_REFERER'] . '";
  340. //-->
  341. </script>';
  342. exit;
  343. }
  344. #取得系统当前时间
  345. public function Times(){
  346. return str_replace('-', '[jian]', date('Y-m-d H:i:s'));
  347. }
  348. #取得用户IP地址
  349. public function GetIP(){
  350. if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  351. $ip = getenv("HTTP_CLIENT_IP");
  352. else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
  353. $ip = getenv("HTTP_X_FORWARDED_FOR");
  354. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  355. $ip = getenv("REMOTE_ADDR");
  356. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  357. $ip = $_SERVER['REMOTE_ADDR'];
  358. else
  359. $ip = "unknown";
  360. return($ip);
  361. }
  362. //最后关闭数据库连接
  363. public function Close(){
  364. !is_object( $this -> Conn ) or mysqli_close( $this -> Conn );
  365. }
  366. }