<?php

// Set folder permissions to 755
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);

require_once('../globals/config.php');
global $con;
$con = new mysqli($host,$user,$pass,$name);
if ($con->connect_errno) {
    printf("Connect failed: %s\n", $con->connect_error);
    exit();
}

backup_tables($host,$user,$pass,$name,'*',$con);

/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables,$con) {
	//$con = new mysqli($host,$user,$pass,$name);
	
	$return = ''; 
	
	//get all of the tables
	if($tables == '*') {
		$tables = array();
		$result = $con->query('SHOW TABLES');
		while ($row = mysqli_fetch_array($result)) {
			$tables[] = $row[0];
		}
	} else {
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
	
	//cycle through
	foreach($tables as $table) {
		$result = $con->query('SELECT * FROM '.$table);
		$num_fields = mysqli_num_fields($result);
		
		$return.= 'DROP TABLE '.$table.';';
		$row2 = mysqli_fetch_row($con->query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";
		
		for ($i = 0; $i < $num_fields; $i++) {
			while($row = mysqli_fetch_row($result)) {
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j<$num_fields; $j++) {
					$row[$j] = addslashes($row[$j]);
					//$row[$j] = ereg_replace("\n","\\n",$row[$j]);
					$row[$j] = str_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}
	
	//save file
	$handle = fopen('db-backup-'. date("Ymd") .'-'. time() .'-'. (md5(implode(',',$tables))) .'.sql','w+');
	fwrite($handle,$return);
	fclose($handle);
	if ($con) $con->close();
	echo 'BACKUP SUCCESSFUL';
}
?>