<?php

/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*', $outputFile='')
{
	//save file
	if (empty($outputFile))
	{
		$outputFile = 'db-backup-' . $name . '-' . time() . '.sql';
	}

	$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');
		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}

	$handle = fopen($outputFile, 'w+');

	$return = '';
	//cycle through
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM ' . $table);
		$num_fields = mysql_num_fields($result);

		$return .= 'DROP TABLE IF EXISTS `'.$table.'`;';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n" . $row2[1] . ";\n\n";

		fwrite($handle, $return);
		$return = '';

		$times = 0;
		$arr = array();
		while($row = mysql_fetch_row($result))
		{
			if (($times % 100) == 0) {
				$arr = array();
				$return .= "INSERT INTO `" . $table . "` VALUES\n";
				$times = 0;
			}

			$line = "(";
			for($j=0; $j < $num_fields; $j++) 
			{
				$row[$j] = addslashes($row[$j]);
				$row[$j] = ereg_replace("\n","\\n",$row[$j]);

				if (isset($row[$j]))
				{
					$line .= '"' . $row[$j] . '"';
				}
				else
				{
					$line .= '""';
				}
				if ($j < ($num_fields-1))
				{
					$line .= ',';
				}
			}
			$line .= ")";
			$arr[] = $line;
			$times++;

			if (($times % 100) == 0 && !empty($arr)) {
				$return .= implode(",\n", $arr);
				$return .= ';' . PHP_EOL;

				fwrite($handle, $return);
				$return = '';
			}
		}
		if (!empty($arr)) {
			$return .= implode(",\n", $arr);
			$return .= ';' . PHP_EOL;
		}
		$return .= "\n\n\n";

		fwrite($handle, $return);
		$return = '';
	}

	fclose($handle);
}

