Last active
June 10, 2016 06:42
-
-
Save ashokmhrj/dbfe895ecbd2fae92fb5 to your computer and use it in GitHub Desktop.
Importing tables structures and data using php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Importing tables structures and data using php | |
*/ | |
function backup_database( $tables = '*' ){ | |
try{ | |
$conn = mysqli_connect($host_name, $username, $password, $dbname); | |
//get all of the tables | |
if($tables == '*') { | |
$tables = array(); | |
$result = mysqli_query( $conn , 'SHOW TABLES' ); | |
while($row = mysqli_fetch_row($result)) { | |
$tables[] = $row[0]; | |
} | |
} else { | |
$tables = is_array($tables) ? $tables : explode(',',$tables); | |
} | |
//cycle through | |
$return = ''; | |
foreach($tables as $table) { | |
$result = mysqli_query( $conn ,'SELECT * FROM '.$table ); | |
$num_fields = mysqli_num_fields($result); | |
$return.= 'DROP TABLE IF EXISTS `'.$table.'`;'; | |
$row2 = mysqli_fetch_row( mysqli_query( $conn ,'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] = mysqli_real_escape_string( $conn, $row[$j] ); | |
// $row[$j] = preg_replace( "/\n/i","\\n",$row[$j] ); | |
// $row[$j] = preg_replace( "/\n/i","\\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('backup/sql/db-backup-'.date('Y-m-d').'.sql','w+'); | |
fwrite($handle,$return); | |
fclose($handle); | |
// sql generated successfully | |
echo "sql"; | |
} catch ( Exception $e ){ | |
// catch message | |
// unable to generate | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment