hi friends, i want to get backup from MySQL DB by use php code.

Hello There, I had found this script of the web, though I don't remember where now, anyway here's what I use.

<?
define('SERVER', 'localhost');  //Your server host
define('USRNAME', 'root');  //Your DB user name
define('PASS', 'Your Pass');  //Your db Password
define('DBNAME', 'db_name');  //You db name


  $ccyymmdd = date("Ymd");
  $file = fopen("backups/backup".$ccyymmdd.".sql","w");
  $line_count = create_backup_sql($file);
  fclose($file);
  $message = "Backup Complete<br />lines written: ".$line_count;

  function create_backup_sql($file) {
    $line_count = 0;
    $db_connection = db_connect();
    mysql_select_db (db_name()) or exit();
    $tables = mysql_list_tables(db_name());
    $sql_string = NULL;
    while ($table = mysql_fetch_array($tables)) {   
      $table_name = $table[0];
      $sql_string = "TRUNCATE TABLE $table_name";
      $table_query = mysql_query("SELECT * FROM `$table_name`");
      $num_fields = mysql_num_fields($table_query);
      while ($fetch_row = mysql_fetch_array($table_query)) {
        $sql_string .= "INSERT INTO $table_name VALUES(";
        $first = TRUE;
        for ($field_count=1;$field_count<=$num_fields;$field_count++){
          if (TRUE == $first) {
            $sql_string .= "'".mysql_real_escape_string($fetch_row[($field_count - 1)])."'";
            $first = FALSE;            
          } else {
            $sql_string .= ", '".mysql_real_escape_string($fetch_row[($field_count - 1)])."'";
          }
        }
        $sql_string .= ");";
        if ($sql_string != ""){
          $line_count = write_backup_sql($file,$sql_string,$line_count);        
        }
        $sql_string = NULL;
      }    
    }
    return $line_count;
  }

  function write_backup_sql($file, $string_in, $line_count) { 
    fwrite($file, $string_in);
    return ++$line_count;
  }
  
  function db_name() {
      return (DBNAME);
  }
  
  function db_connect() {
    $db_connection = mysql_connect(SERVER, USRNAME, PASS);
    return $db_connection;
  }  
?>

This script will write a backup file named with the date and a prefix of backup in your backups folder. I hope this helps. If needed I also have a restore from backup script.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.