How to backup/export the connected Database database.sql file in laravel?
Solution 1
// Code
public function our_backup_database(){
//ENTER THE RELEVANT INFO BELOW
$mysqlHostName = env('DB_HOST');
$mysqlUserName = env('DB_USERNAME');
$mysqlPassword = env('DB_PASSWORD');
$DbName = env('DB_DATABASE');
$backup_name = "mybackup.sql";
$tables = array("users","messages","posts"); //here your tables...
$connect = new \PDO("mysql:host=$mysqlHostName;dbname=$DbName;charset=utf8", "$mysqlUserName", "$mysqlPassword",array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$get_all_table_query = "SHOW TABLES";
$statement = $connect->prepare($get_all_table_query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($tables as $table)
{
$show_table_query = "SHOW CREATE TABLE " . $table . "";
$statement = $connect->prepare($show_table_query);
$statement->execute();
$show_table_result = $statement->fetchAll();
foreach($show_table_result as $show_table_row)
{
$output .= "\n\n" . $show_table_row["Create Table"] . ";\n\n";
}
$select_query = "SELECT * FROM " . $table . "";
$statement = $connect->prepare($select_query);
$statement->execute();
$total_row = $statement->rowCount();
for($count=0; $count<$total_row; $count++)
{
$single_result = $statement->fetch(\PDO::FETCH_ASSOC);
$table_column_array = array_keys($single_result);
$table_value_array = array_values($single_result);
$output .= "\nINSERT INTO $table (";
$output .= "" . implode(", ", $table_column_array) . ") VALUES (";
$output .= "'" . implode("','", $table_value_array) . "');\n";
}
}
$file_name = 'database_backup_on_' . date('y-m-d') . '.sql';
$file_handle = fopen($file_name, 'w+');
fwrite($file_handle, $output);
fclose($file_handle);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_name));
ob_clean();
flush();
readfile($file_name);
unlink($file_name);
}
// routing
Route::get('/our_backup_database', 'YourControllerController@our_backup_database')->name('our_backup_database');
//View
<form action="{{ route('our_backup_database') }}" method="get">
<button style="submit" class="btn btn-primary"> download</button>
</form>
Solution 2
Route::get('/backupdb', function () {
$DbName = env('DB_DATABASE');
$get_all_table_query = "SHOW TABLES ";
$result = DB::select(DB::raw($get_all_table_query));
$prep = "Tables_in_$DbName";
foreach ($result as $res){
$tables[] = $res->$prep;
}
$connect = DB::connection()->getPdo();
$get_all_table_query = "SHOW TABLES";
$statement = $connect->prepare($get_all_table_query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($tables as $table)
{
$show_table_query = "SHOW CREATE TABLE " . $table . "";
$statement = $connect->prepare($show_table_query);
$statement->execute();
$show_table_result = $statement->fetchAll();
foreach($show_table_result as $show_table_row)
{
$output .= "\n\n" . $show_table_row["Create Table"] . ";\n\n";
}
$select_query = "SELECT * FROM " . $table . "";
$statement = $connect->prepare($select_query);
$statement->execute();
$total_row = $statement->rowCount();
for($count=0; $count<$total_row; $count++)
{
$single_result = $statement->fetch(\PDO::FETCH_ASSOC);
$table_column_array = array_keys($single_result);
$table_value_array = array_values($single_result);
$output .= "\nINSERT INTO $table (";
$output .= "" . implode(", ", $table_column_array) . ") VALUES (";
$output .= "'" . implode("','", $table_value_array) . "');\n";
}
}
$file_name = 'database_backup_on_' . date('y-m-d') . '.sql';
$file_handle = fopen($file_name, 'w+');
fwrite($file_handle, $output);
fclose($file_handle);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_name));
ob_clean();
flush();
readfile($file_name);
unlink($file_name);
});
Solution 3
I've tweaked @Abdelhakim Ezzahouri's code, to use Laravel's existing connection to DB instead of connecting again, entering credentials, and installing PDO, if it's not installed already.
Route::get('db_dump', function () {
/*
Needed in SQL File:
SET GLOBAL sql_mode = '';
SET SESSION sql_mode = '';
*/
$get_all_table_query = "SHOW TABLES";
$result = DB::select(DB::raw($get_all_table_query));
$tables = [
'admins',
'migrations',
];
$structure = '';
$data = '';
foreach ($tables as $table) {
$show_table_query = "SHOW CREATE TABLE " . $table . "";
$show_table_result = DB::select(DB::raw($show_table_query));
foreach ($show_table_result as $show_table_row) {
$show_table_row = (array)$show_table_row;
$structure .= "\n\n" . $show_table_row["Create Table"] . ";\n\n";
}
$select_query = "SELECT * FROM " . $table;
$records = DB::select(DB::raw($select_query));
foreach ($records as $record) {
$record = (array)$record;
$table_column_array = array_keys($record);
foreach ($table_column_array as $key => $name) {
$table_column_array[$key] = '`' . $table_column_array[$key] . '`';
}
$table_value_array = array_values($record);
$data .= "\nINSERT INTO $table (";
$data .= "" . implode(", ", $table_column_array) . ") VALUES \n";
foreach($table_value_array as $key => $record_column)
$table_value_array[$key] = addslashes($record_column);
$data .= "('" . implode("','", $table_value_array) . "');\n";
}
}
$file_name = __DIR__ . '/../database/database_backup_on_' . date('y_m_d') . '.sql';
$file_handle = fopen($file_name, 'w + ');
$output = $structure . $data;
fwrite($file_handle, $output);
fclose($file_handle);
echo "DB backup ready";
});
Solution 4
one of the best solution
-
fisrt of all install spatie on local server https://spatie.be/docs/laravel-backup/v6/installation-and-setup
-
now check backup working or not
php artisan backup:run
-
if backup success then u can also take it on cpanel for this go ro app/Console/Kernal.php and register this command
protected function schedule(Schedule $schedule) { $schedule->command('backup:run')->everyMinute(); }
-
now open your cpanel and open cron job and there register this command
/usr/local/bin/php /home/replaceyourdirectoryname/public_html/artisan backup:run > /dev/null 2>&1
-
now you are successful able to take backup on live server
-
now for on clcik download
<a href="{{ route('download') }}" class="btn btn-sm btn-primary"><i class="fa fa-download"></i>Download Backup</a>
-
register route
Route::get('/download/','DownloadController@download')->name('download');
-
and finally controller
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Artisan; class DownloadController extends Controller{ public function download(){ Artisan::call('backup:run'); $path = storage_path('app/laravel-backup/*'); $latest_ctime = 0; $latest_filename = ''; $files = glob($path); foreach($files as $file) { if (is_file($file) && filectime($file) > $latest_ctime) { $latest_ctime = filectime($file); $latest_filename = $file; } } return response()->download($latest_filename); }
}
Solution 5
Thanks for @Abdelhakim Ezzahraoui for your solution. i have just change some code. so here you can backup all table. but if you want specific then you set that table name.
function backupDatabase()
{
//ENTER THE RELEVANT INFO BELOW
$mysqlHostName = env('DB_HOST');
$mysqlUserName = env('DB_USERNAME');
$mysqlPassword = env('DB_PASSWORD');
$DbName = env('DB_DATABASE');
$file_name = 'database_backup_on_' . date('y-m-d') . '.sql';
$queryTables = \DB::select(\DB::raw('SHOW TABLES'));
foreach ( $queryTables as $table )
{
foreach ( $table as $tName)
{
$tables[]= $tName ;
}
}
// $tables = array("users","products","categories"); //here your tables...
$connect = new \PDO("mysql:host=$mysqlHostName;dbname=$DbName;charset=utf8", "$mysqlUserName", "$mysqlPassword",array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$get_all_table_query = "SHOW TABLES";
$statement = $connect->prepare($get_all_table_query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($tables as $table)
{
$show_table_query = "SHOW CREATE TABLE " . $table . "";
$statement = $connect->prepare($show_table_query);
$statement->execute();
$show_table_result = $statement->fetchAll();
foreach($show_table_result as $show_table_row)
{
$output .= "\n\n" . $show_table_row["Create Table"] . ";\n\n";
}
$select_query = "SELECT * FROM " . $table . "";
$statement = $connect->prepare($select_query);
$statement->execute();
$total_row = $statement->rowCount();
for($count=0; $count<$total_row; $count++)
{
$single_result = $statement->fetch(\PDO::FETCH_ASSOC);
$table_column_array = array_keys($single_result);
$table_value_array = array_values($single_result);
$output .= "\nINSERT INTO $table (";
$output .= "" . implode(", ", $table_column_array) . ") VALUES (";
$output .= "'" . implode("','", $table_value_array) . "');\n";
}
}
$file_handle = fopen($file_name, 'w+');
fwrite($file_handle, $output);
fclose($file_handle);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_name));
ob_clean();
flush();
readfile($file_name);
unlink($file_name);
}
ppegu
Updated on July 01, 2022Comments
-
ppegu over 1 year
I have viewed all the topics available for this question , but not getting any acurate answer... anybody got clear idea to backup the current database in .sql file and download it ?
-
Amin over 3 yearsThanks for the great idea, I've modified your code above to use Laravel's existing DB connection, no need to re-enter credentials or use PDO extension if it's not installed (in my case it wasn't)
-
Mrinal Roy over 3 yearsPlease fix the code formatting and explain why your answer is different and better than others above and also voted higher
-
Idris Akbar Adyusman almost 3 yearsadd
wordwrap()
to wrap the data like this:$data .= "('" . wordwrap(implode("','", $table_value_array),400,"\n",TRUE) . "');\n";
. if the data gets too long that exceeded the limit of a line, it will be truncated and resulting error when you try to import it back into your database -
Martin Eckleben almost 3 yearsWhat I do like about this answer is that it actually exports all tables and not only two constant ones as in @Amins answer.
-
Naeem Ijaz almost 3 yearssir this is working offline correctly. but online it is not working