A simple integrated class of database connection and text cache

Source: Internet
Author: User
A simple integrated class of database connection and text cache
The database connection and text cache are encapsulated in a class.

  1. Class Db {
  2. Protected $ _ connect;
  3. Protected $ _ db = Array ();
  4. Protected $ _ cache = Array ();
  5. Public function _ construct ($ args ){
  6. List ($ this-> _ db, $ this-> _ cache) = $ args;
  7. }
  8. Protected function connect ($ db ){
  9. $ This-> _ connect = mysql_connect ($ db ['hostname'], $ db ['username'], $ db ['password']);
  10. Mysql_set_charset ('utf8 ');
  11. Mysql_select_db ($ db ['databasename '], $ this-> _ connect );
  12. }
  13. /**
  14. * Function: obtain the table data and format the queried data. the returned format is an array!
  15. * $ SQL: the input SQL statement to be executed, which must be SELECT
  16. *
  17. */
  18. Public function fetch ($ SQL ){
  19. $ Result = '';
  20. If (isset ($ this-> _ cache ['expire ']) {
  21. $ Name = md5 (strtolower (str_replace ('','', $ SQL )));
  22. $ Dir = substr ($ name, 0, 2 );
  23. $ Dir = $ this-> _ cache ['dir']. '/'. $ dir;
  24. ! Is_dir ($ dir) & mkdir ($ dir, 0777 );
  25. ! Is_dir ($ dir) & mkdir ($ dir, 0777 );
  26. $ This-> _ cache ['path'] = $ dir. '/'. $ name;
  27. If (is_file ($ this-> _ cache ['path']) & $ this-> check_expire ()){
  28. $ Result = $ this-> get ();
  29. }
  30. }
  31. If ($ result = ''){
  32. $ Data = $ this-> exec ($ SQL );
  33. $ Result = Array ();
  34. While ($ result [] = mysql_fetch_array ($ data, MYSQL_ASSOC) {}// remove the index
  35. Mysql_free_result ($ data );
  36. Array_pop ($ result );
  37. Isset ($ this-> _ cache ['expire ']) & $ this-> write ($ result );
  38. }
  39. Return $ result;
  40. }
  41. /**
  42. * Function: execute all SQL statements, but not SELECT!
  43. * $ SQL: the input SQL statement to be executed. it cannot be a SELECT statement.
  44. * Return value: TRUE OR FALSE
  45. */
  46. Public function exec ($ SQL ){
  47. If ($ this-> _ connect === null) $ this-> connect ($ this-> _ db); // data link
  48. If ($ result = mysql_query ($ SQL, $ this-> _ connect )){
  49. Return $ result;
  50. } Else {
  51. Die ("{$ SQL}
    Execution error: ". mysql_error ());
  52. }
  53. }
  54. /**
  55. * Function: execute the database INSERT statement. it can only be an INSERT statement!
  56. * $ V: The input condition to be executed. in the array format, table indicates the table to be inserted, row indicates the field, and value indicates the value to be inserted.
  57. * Return value: mysql_insert_id () OR FALSE
  58. */
  59. Public function insert ($ table, $ field, $ ignore = 0 ){
  60. $ D = Array ('field' => '', 'Val' => '');
  61. Foreach ($ field AS $ key => $ v ){
  62. $ D ['field']. = $ key .',';
  63. $ D ['Val']. = "'{$ this-> escape ($ v )}',";
  64. }
  65. $ D ['field'] = rtrim ($ D ['field'], ',');
  66. $ D ['Val'] = rtrim ($ D ['Val'], ',');
  67. $ Ignore = $ ignore> 0? 'Ignore ':'';
  68. $ SQL = "INSERT {$ ignore} INTO {$ this-> _ db ['perfix']} {$ table} ({$ D ['field']}) VALUES ({$ D ['Val']}) ";
  69. If ($ this-> exec ($ SQL )){
  70. $ Insert_id = mysql_insert_id ();
  71. Return is_numeric ($ insert_id )? $ Insert_id: TRUE;
  72. } Else {
  73. Return FALSE;
  74. }
  75. }
  76. Public function update ($ table, $ field ){
  77. $ D = Array ('where' => '', 'str' => '');
  78. $ Index = 0;
  79. Foreach ($ field AS $ key => $ v ){
  80. $ Index = 0? $ D ['where'] = "{$ key} = '{$ this-> escape ($ v)}'": $ D ['str']. = "{$ key} = '{$ this-> escape ($ v )}',";
  81. $ Index ++;
  82. }
  83. $ D ['str'] = rtrim ($ D ['str'], ',');
  84. $ SQL = "UPDATE {$ this-> _ db ['perfix']} {$ table} SET {$ D ['str']} WHERE {$ D ['where' ]} ";
  85. Return $ this-> exec ($ SQL );
  86. }
  87. Public function delete ($ table, $ field ){
  88. $ Str = '';
  89. Foreach ($ field AS $ key => $ v ){
  90. $ Str = "{$ key} = '{$ v }'";
  91. }
  92. $ SQL = 'delete from'. $ this-> _ db ['perfix']. $ table. 'where'. $ str. 'limit 1 ';
  93. Return $ this-> exec ($ SQL );
  94. }
  95. Public function sum ($ table, $ condition ){
  96. $ Totle = $ this-> fetch ('SELECT COUNT (*) AS totle FROM '. $ this-> _ db ['perfix']. $ table. 'Where '. $ condition );
  97. Return $ totle [0] ['totle '];
  98. }
  99. /**
  100. * Function: filter out special characters.
  101. * $ V: parameters to be passed in for detection
  102. * Return value: the detected parameter.
  103. */
  104. Public function escape ($ v ){
  105. Return mysql_real_escape_string ($ v );
  106. }
  107. /*
  108. * Function: determines the cache.
  109. */
  110. Public function cache ($ name, $ expire = 100000000 ){
  111. $ This-> _ cache ['expire '] = $ expire;
  112. Return $ this;
  113. }
  114. Public function check_expire (){
  115. Return (filemtime ($ this-> _ cache ['path']) + $ this-> _ cache ['expire '])> strtotime ("now ");
  116. }
  117. Public function write ($ data ){
  118. $ F = fopen ($ this-> _ cache ['path'], 'w ');
  119. If ($ f ){
  120. Flock ($ f, LOCK_EX );
  121. Fseek ($ f, 0 );
  122. Ftruncate ($ f, 0 );
  123. $ Tmp = fwrite ($ f, serialize ($ data ));
  124. If (! ($ Tmp = false )){
  125. $ Result = true;
  126. }
  127. Fclose ($ f );
  128. }
  129. Chmod ($ this-> _ cache ['path'], 0777 );
  130. }
  131. Public function get (){
  132. $ F = fopen ($ this-> _ cache ['path'], 'r ');
  133. $ Data = fread ($ f, filesize ($ this-> _ cache ['path']);
  134. Fclose ($ f );
  135. Return unserialize ($ data );
  136. }
  137. Public function delete_dir ($ dir = ''){
  138. $ Dir = empty ($ dir )? $ This-> _ cache ['dir']: $ dir;
  139. ! Is_dir ($ dir) & exit;
  140. $ D = opendir ($ dir );
  141. $ I = 0;
  142. While ($ file = readdir ($ d ))! = False ){
  143. $ Path = $ dir. '/'. $ file;
  144. If ($ I> 1) is_file ($ path )? Unlink ($ path): $ this-> delete_dir ($ path );
  145. $ I ++;
  146. }
  147. Closedir ($ d );
  148. Rmdir ($ dir );
  149. }
  150. Public function _ destruct (){
  151. Isset ($ this-> _ connect) & mysql_close ($ this-> _ connect );
  152. }
  153. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.