Php backs up the entire MySQL database or specifies a table

Source: Internet
Author: User
Tags create zip create zip file ziparchive
Php backs up the entire MySQL database or specifies a table

Php class implements full backup of the database, or the function of backing up the specified table in the database:

  1. Class Backup
  2. {
  3. /**
  4. * @ Var stores the options
  5. */
  6. Var $ config;
  7. /**
  8. * @ Var stores the final SQL dump
  9. */
  10. Var $ dump;
  11. /**
  12. * @ Var stores the table structure + inserts for every table
  13. */
  14. Var $ struktur = array ();
  15. /**
  16. * @ Var zip file name
  17. */
  18. Var $ datei;
  19. /**
  20. * This function is the constructor and phrase the options
  21. * And connect to the database
  22. * @ Return
  23. */
  24. Public function Backup ($ options)
  25. {
  26. // Write options
  27. Foreach ($ options AS $ name => $ value)
  28. {
  29. $ This-> config [$ name] = $ value;
  30. }
  31. // Check mysql connection
  32. Mysql_connect ($ this-> config ['mysql'] [0], $ this-> config ['mysql'] [1], $ this-> config ['mysql'] [2]) or die (mysql_error ());
  33. Mysql_select_db ($ this-> config ['mysql'] [3]) or die (mysql_error ());
  34. }
  35. /**
  36. * This function starts the backup progress its core function
  37. * @ Return
  38. */
  39. Public function backupDB ()
  40. {
  41. // Start backup
  42. If (isset ($ _ POST ['backup '])
  43. {
  44. // Check if tables are selected
  45. If (empty ($ _ POST ['table'])
  46. {
  47. Die ("Please select a table .");
  48. }
  49. /** Start backup **/
  50. $ Tables = array ();
  51. $ Insert = array ();
  52. $ SQL _statement = '';
  53. // Lock tables
  54. Foreach ($ _ POST ['table'] AS $ table)
  55. {
  56. Mysql_query ("lock table $ table WRITE ");
  57. // Read table structure
  58. $ Res = mysql_query ('Show CREATE Table'. $ TABLE .'');
  59. $ Createtable = mysql_result ($ res, 0, 1 );
  60. $ Str = "\ n". $ createtable. "\ n ";
  61. Array_push ($ tables, $ str );
  62. // Read table "inserts"
  63. $ SQL = 'select * from'. $ table;
  64. $ Query = mysql_query ($ SQL) or die (mysql_error ());
  65. $ Feld_anzahl = mysql_num_fields ($ query );
  66. $ SQL _statement = '--
  67. -- Data Table '$ table'
  68. --
  69. ';
  70. // Start reading progress
  71. While ($ ds = mysql_fetch_object ($ query )){
  72. $ SQL _statement. = 'Insert INTO '''. $ table .''(';
  73. For ($ I = 0; $ I <$ feld_anzahl; $ I ++ ){
  74. If ($ I ==$ feld_anzahl-1 ){
  75. $ SQL _statement. = mysql_field_name ($ query, $ I );
  76. } Else {
  77. $ SQL _statement. = mysql_field_name ($ query, $ I ).',';
  78. }
  79. }
  80. $ SQL _statement. = ') VALUES (';
  81. For ($ I = 0; $ I <$ feld_anzahl; $ I ++ ){
  82. $ Name = mysql_field_name ($ query, $ I );
  83. If (empty ($ ds-> $ name )){
  84. $ Ds-> $ name = 'null ';
  85. }
  86. If ($ I ==$ feld_anzahl-1 ){
  87. $ SQL _statement. = '"'. $ ds-> $ name .'"';
  88. } Else {
  89. $ SQL _statement. = '"'. $ ds-> $ name .'",';
  90. }
  91. }
  92. $ SQL _statement. = "); \ n ";
  93. }
  94. // Insert "Inserts" into an array if not exists
  95. If (! In_array ($ SQL _statement, $ insert ))
  96. {
  97. Array_push ($ insert, $ SQL _statement );
  98. Unset ($ SQL _statement );
  99. }
  100. Unset ($ SQL _statement );
  101. }
  102. // Put table structure and inserts together in one var
  103. $ This-> struktur = array_combine ($ tables, $ insert );
  104. // Create full dump
  105. $ This-> createDUMP ($ this-> struktur );
  106. // Create zip file
  107. $ This-> createZIP ();
  108. /** End backup **/
  109. // Send an email with the SQL dump
  110. If (isset ($ this-> config ['email ']) &! Empty ($ this-> config ['email '])
  111. {
  112. $ This-> sendEmail ();
  113. }
  114. // Output
  115. Echo 'backup war erfolgreichdatei. '"> Download Backup


  116. ';
  117. }
  118. }
  119. /**
  120. * This function generate an email with attachment
  121. * @ Return
  122. */
  123. Protected function sendEmail ()
  124. {
  125. // Start sending emails
  126. Foreach ($ this-> config ['email '] AS $ email)
  127. {
  128. $ To = $ email;
  129. $ From = $ this-> config ['email '] [0];
  130. $ Message_body = "This email contains the database backup as a zip file .";
  131. $ Msep = strtoupper (md5 (uniqid (time ())));
  132. // Set email header (only text)
  133. $ Header =
  134. "From: $ from \ r \ n ".
  135. "MIME-Version: 1.0 \ r \ n ".
  136. "Content-Type: multipart/mixed; boundary =" $ msep "\ r \ n ".
  137. "-- $ Msep \ r \ n ".
  138. "Content-Type: text/plain \ r \ n ".
  139. "Content-Transfer-Encoding: 8bit \ r \ n ".
  140. $ Message_body. "\ r \ n ";
  141. // File name
  142. $ Dateiname = $ this-> datei;
  143. // Get filesize of zip file
  144. $ Dateigroesse = filesize ($ dateiname );
  145. // Open file to read
  146. $ F = fopen ($ dateiname, "r ");
  147. // Save content
  148. $ Attached_file = fread ($ f, $ dateigroesse );
  149. // Close file
  150. Fclose ($ f );
  151. // Create attachment
  152. $ Attachment = chunk_split (base64_encode ($ attached_file ));
  153. // Set attachment header
  154. $ Header. =
  155. "--". $ Msep. "\ r \ n ".
  156. "Content-Type: application/zip; name = 'backup '\ r \ n ".
  157. "Content-Transfer-Encoding: base64 \ r \ n ".
  158. "Content-Disposition: attachment; filename='Backup.zip '\ r \ n ".
  159. "Content-Description: Mysql Datenbank Backup im Anhang \ r \ n ".
  160. $ Attachment. "\ r \ n ";
  161. // Mark end of attachment
  162. $ Header. = "-- $ msep --";
  163. // EMail Subject
  164. $ Subject = "Database Backup ";
  165. // Send email to emails ^
  166. If (mail ($ to, $ subject, '', $ header) = FALSE)
  167. {
  168. Die ("The email cocould not be sent. Please check the email address .");
  169. }
  170. Echo"

    Email was successfully sent.

    ";
  171. }
  172. }
  173. /**
  174. * This function create the zip file with the database dump and save it on the ftp server
  175. * @ Return
  176. */
  177. Protected function createZIP ()
  178. {
  179. // Set permissions to 777
  180. Chmod ($ this-> config ['Folder'], 0777 );
  181. // Create zip file
  182. $ Zip = new ZipArchive ();
  183. // Create file name
  184. $ This-> datei = $ this-> config ['Folder']. $ this-> config ['mysql'] [3]. "_". date ("j_F_Y_g: I _a "). ". zip ";
  185. // Checking if file cocould be created
  186. If ($ zip-> open ($ this-> datei, ZIPARCHIVE: CREATE )! = TRUE ){
  187. Exit ("cannot open <". $ this-> datei. "> \ n ");
  188. }
  189. // Add mysql dump to zip file
  190. $ Zip-> addFromString ("dump. SQL", $ this-> dump );
  191. // Close file
  192. $ Zip-> close ();
  193. // Check whether file has been created
  194. If (! File_exists ($ this-> datei ))
  195. {
  196. Die ("The ZIP file cocould not be created .");
  197. }
  198. Echo"

    The zip was created.

    ";
  199. }
  200. /**
  201. * This function create the full SQL dump
  202. * @ Param object $ dump
  203. * @ Return
  204. */
  205. Protected function createDUMP ($ dump)
  206. {
  207. $ Date = date ("F j, Y, g: I ");
  208. $ Header = < -- SQL Dump
  209. --
  210. -- Host: {$ _ SERVER ['http _ host']}
  211. -- Erstellungszeit: {$ date}
  212. --
  213. -- Datenbank: '{$ this-> config ['mysql'] [3]}'
  214. --
  215. ----------------------------------------------------------
  216. HEADER;
  217. Foreach ($ dump AS $ name => $ value)
  218. {
  219. $ SQL. = $ name. $ value;
  220. }
  221. $ This-> dump = $ header. $ SQL;
  222. }
  223. /**
  224. * This function displays the output form to select tables
  225. * @ Return
  226. */
  227. Public function outputForm ()
  228. {
  229. // Select all tables from database
  230. $ Result = mysql_list_tables ($ this-> config ['mysql'] [3]);
  231. $ Buffer ='
  232. Select some tables
  233. ';
  234. Echo $ buffer;
  235. }
  236. }
  237. ?>


Backup usage:

  1. // You can add as your email addresses as you like
  2. $ Options = array ('email '=> array ('email1', 'email2 '),
  3. 'Folder' => './backup /',
  4. 'Mysql' => array ('localhost', 'root', '***', 'database '));
  5. $ B = new Backup ($ options );
  6. // If submit form start backup
  7. If (isset ($ _ POST ['backup '])
  8. {
  9. // Start backup
  10. $ B-> backupDB ();
  11. }
  12. // Display tables
  13. $ B-> outputForm ();
  14. ?>


Php, MySQL

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.