Skip to content

Instantly share code, notes, and snippets.

@ashokmhrj
Last active June 10, 2016 06:42
Show Gist options
  • Save ashokmhrj/dbfe895ecbd2fae92fb5 to your computer and use it in GitHub Desktop.
Save ashokmhrj/dbfe895ecbd2fae92fb5 to your computer and use it in GitHub Desktop.
Importing tables structures and data using php
<?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