Home Backend Development PHP Tutorial PHP backs up the entire MySQL database, or specifies the table

PHP backs up the entire MySQL database, or specifies the table

Jul 25, 2016 am 08:45 AM

The php class implements the function of fully backing up the database, or backing up specified tables 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 start the backup progress its the 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 = "nn".$createtable."nn";
  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 erfolgreich

    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: $fromrn" .
  135. "MIME-Version: 1.0rn" .
  136. "Content-Type: multipart/mixed; boundary="$msep"rnrn" .
  137. "--$mseprn" .
  138. "Content-Type: text/plainrn" .
  139. "Content-Transfer-Encoding: 8bitrnrn" .
  140. $message_body . "rn";
  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 . "rn" .
  156. "Content-Type: application/zip; name='Backup'rn" .
  157. "Content-Transfer-Encoding: base64rn" .
  158. "Content-Disposition: attachment; filename='Backup.zip'rn" .
  159. "Content-Description: Mysql Datenbank Backup im Anhangrnrn" .
  160. $attachment . "rn";
  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 could 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 could 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 could 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 a");
  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. ?>
复制代码

备份用法:
  1. //You can add as many 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


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles