toss82

DUMP MYSQL TABLE FROM PHP

Mar 15th, 2013
451
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.81 KB | None | 0 0
  1. <?php
  2.     /*
  3.     * DUMP MYSQL TABLE FROM PHP
  4.     * credits:
  5.     * David Walsh - original script http://davidwalsh.name/backup-mysql-database-php
  6.     * Emanuele "ToX" Toscano - single insert into instruction for many rows, dump & create table functions
  7.     */
  8.     function dumpTable($host, $user, $pass, $db, $table) {
  9.         $return = null;
  10.         $link = mysql_connect($host, $user, $pass);
  11.         mysql_select_db($db, $link);
  12.        
  13.         $result     = mysql_query('SELECT * FROM ' . $table);
  14.         $num_fields = mysql_num_fields($result);
  15.        
  16.         /* DUMP TABLE (uncomment if you need it) *\/
  17.             $return.='DROP TABLE ' . $table . ';';
  18.  
  19.         /* CREATE TABLE (uncomment if you need it) *\/
  20.             $row2=mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
  21.             $return.="\n\n" . $row2[1] . ";\n\n";
  22.        
  23.         /* INSERT INTO instructions */
  24.             if ($num_fields > 0) {
  25.                 $return.='INSERT INTO ' . $table . ' VALUES';
  26.                 for ($i=0; $i<$num_fields; $i++) {
  27.                     $x = 0;
  28.                     while ($row=mysql_fetch_row($result)) {
  29.                         $x++;
  30.                         if ($x == 1) {
  31.                             $return .= "\n(";
  32.                         } else {
  33.                             $return .= "),\n(";
  34.                         }
  35.                         for ($j=0; $j<$num_fields; $j++) {
  36.                             $row[$j]=addslashes($row[$j]);
  37.                             $row[$j]=str_replace("\n", "\\n", $row[$j]);
  38.                             if (isset($row[$j])) {
  39.                                 $return.='"' . $row[$j] . '"';
  40.                             } else {
  41.                                 $return.='""';
  42.                             }
  43.                             if ($j<($num_fields-1)) {
  44.                                 $return.=',';
  45.                             }
  46.                         }
  47.                     }
  48.                 }
  49.                 $return.=");\n";
  50.             }
  51.                
  52.         return $return;
  53.     }
Add Comment
Please, Sign In to add comment