Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function mysql_to_file($host, $user, $pass, $name, $tables = '*', $to_file = "")
- {
- $link = mysql_connect($host, $user, $pass);
- mysql_select_db($name, $link);
- // get all of the tables
- if($tables == '*')
- {
- $tables = array();
- $result = mysql_query('SHOW TABLES', $link);
- while($row = mysql_fetch_row($result))
- {
- $tables[] = $row[0];
- }
- }
- else
- {
- $tables = is_array($tables) ? $tables : explode(',', $tables);
- }
- $handle = null;
- if ($to_file == "")
- $handle = fopen($name.'.sql','w+');
- else
- $handle = fopen($to_file,'w+');
- fwrite($handle, "--\n");
- fwrite($handle, "-- Database: `'.$name.'`\n");
- fwrite($handle, "--\n\n");
- // loop through the tables
- foreach($tables as $table)
- {
- $return = "";
- $columns = array();
- $result = mysql_query('SELECT * FROM `'.$table.'`', $link);
- $num_fields = mysql_num_fields($result);
- $return = "--\n";
- $return .= "-- Table structure for table `".$table."`\n";
- $return .= "--\n\n";
- $return.= 'DROP TABLE IF EXISTS `'.$table.'`;'."\n";
- $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE `'.$table.'`', $link));
- $return.= "\n".$row2[1].";\n\n";
- // gather the columns for values to inset into
- $column_split = explode("\n", $row2[1]);
- foreach ($column_split as $split_value)
- {
- $splitString = explode(" ", trim($split_value));
- if ($splitString[0] == "CREATE") continue;
- if ($splitString[0] == "PRIMARY") break;
- $columns[count($columns)] = $splitString[0];
- }
- $column_names = "";
- foreach ($columns as $key => $name)
- {
- if ($key + 1 == count($columns))
- $column_names .= $name;
- else
- $column_names .= $name.', ';
- }
- $return .= "--\n";
- $return .= "-- Dumping data for table `".$table."`\n";
- $return .= "--\n\n";
- for ($i = 0; $i < $num_fields; $i++)
- {
- while($row = mysql_fetch_row($result))
- {
- $return.= 'INSERT INTO `'.$table.'` ('.$column_names.') VALUES (';
- for($j = 0; $j < $num_fields; $j++)
- {
- $row[$j] = addslashes($row[$j]);
- //$row[$j] = preg_replace("\n","\\n",$row[$j]);
- if (isset($row[$j]))
- {
- if (is_numeric($row[$j]))
- $return.= $row[$j];
- else
- $return.= "'".$row[$j]."'";
- }
- else
- {
- $return.= "''";
- }
- if ($j < ($num_fields - 1))
- {
- $return.= ', ';
- }
- }
- $return.= ");\n";
- }
- }
- $return.="\n";
- fwrite($handle, $return);
- }
- fclose($handle);
- }
- ?>
Add Comment
Please, Sign In to add comment