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 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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles