简体   繁体   中英

Backup DB from php

I'm testing this script on the local server

$dump_path = "backups"; 
$host = "localhost";  
$user = "root";  
$pass = "";  
$command=$dump_path.'mysqldump -h '.$host.' -u '.$user.' dental > dental_b.sql';
if  (system($command)) {
  echo "YES" ; 
} else {
  echo "Error" ;
}

But why isn't that script executed and shows an error although all data from the DB is true.

I'm pretty sure you don't need the host option if you're using mysqldump on localhost. The way you are concatenating your command looks messed up to me. Let me show you what works for me. I use this all the time:

<?php

$user = "root";  
$pass = "";
$database = "dental";

// File name
$file_name = 'dental_b.' . date('mdY.Hia') . '.sql.gz';

// Storage directory
$storage_dir = __DIR__ . '/backups';
if( ! is_dir( $storage_dir ) )
    mkdir( $storage_dir, 0777, TRUE );

// Absolute path to new file
$absolute_path = $storage_dir . '/' . $file_name;

// Create the backup file
exec( 'mysqldump -u ' . $user . 
    ' -p' . $pass . 
    ' ' . $database . 
    ' | gzip > ' . $absolute_path );

Yes, I am gzipping the file. I think you'll find this is a good option for storage, emailing, etc.

EDIT ---

If you are not using a password, you should not use -p. You'd want to alter the command in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM