<?php

/**
* Updated: Mohammad M. AlBanna
* Website: MBanna.info
*/

ini_set('display_errors', false);

error_reporting(-1);

set_error_handler(function($code, $string, $file, $line){
        throw new ErrorException($string, null, $code, $file, $line);
    });

register_shutdown_function(function(){
        $error = error_get_last();
        if(null !== $error)
        {
           // echo 'Failed to download';
		echo "<script>alert('Failed to Download');</script>";
		echo "<script>window.location.href='backup.php?ret=f';</script>";
       exit;
        }
    });

///MySQL server and database
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'thahaayaa';
$tables = '*';

 //$link1 = mysqli_connect($dbhost,$dbuser,$dbpass, $dbname);

//$result = mysqli_query($link1, 'SHOW TABLES');
$count = "84";//mysqli_num_rows($result);
$first_split = ceil($count / 2); // => 30

$from_table = '0';
$to_table=$first_split;
$fno=1;

$from_table1 = $first_split+1;
$to_table1=$count;
$fno1=2;
 
//Call the core function
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables,$from_table,$to_table,$fno);
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables,$from_table1,$to_table1,$fno1);


//Core function
function backup_tables($host, $user, $pass, $dbname, $tables = '*',$from_table,$to_table,$fno) {
    $link = mysqli_connect($host,$user,$pass, $dbname);
	try
{

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        exit;
    }

    mysqli_query($link, "SET NAMES 'utf8'");

    //get all of the tables
    if($tables == '*')
    {
        $tables = array();
        $result = mysqli_query($link, 'SHOW TABLES');
		$ui=0;
        while($row = mysqli_fetch_row($result))
        {
			if($ui>$from_table && $ui<$to_table){
            $tables[] = $row[0];
			}
			$ui++;
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    $return = '';
    //cycle through
    foreach($tables as $table)
    {
        $result = mysqli_query($link, 'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $num_rows = mysqli_num_rows($result);

        $return.= 'DROP TABLE IF EXISTS '.$table.';';
        $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
        $counter = 1;

        //Over tables
        for ($i = 0; $i < $num_fields; $i++) 
        {   //Over rows
            while($row = mysqli_fetch_row($result))
            {
                if($counter == 1){
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                } else{
                    $return.= '(';
                }

				//Over fields
                for($j=0; $j<$num_fields; $j++) 
                {
                    $row[$j] = addslashes($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.= ','; }
                }

               if($num_rows == $counter){
                    $return.= ");\n";
                } else{
                    $return.= "),\n";
                }

				++$counter;
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $fileName = 'db-backup-'.$fno.'-'.time().'-'.(md5(implode(',',$tables))).'.sql';
    $handle = fopen($fileName,'w+');
    fwrite($handle,$return);
    if(fclose($handle)){
       // echo "Done, the file name is: ".$fileName;
	   echo "<script>alert('Done');</script>";
	   echo "<script>window.location.href='backup.php?ret=s';</script>";
      // exit;
    } 
	}
catch(\Exception $exception)
{
   // echo 'Caught in try/catch';
		echo "<script>alert('Failed to Download');</script>";
	   echo "<script>window.location.href='backup.php';</script>";
     //  exit;
}

}
