简体   繁体   中英

how to copy mysql DB from localhost to server using php?

I have a php project running in my local machine(angular,php,mysql).Same copy of project running in online. My Aim is to Sync(copy local db to server db) every one hour by running any PHP Script using angular 'set Interval' function. What is the IDEA behind this functionality should i use? or how i will achieve this ? Any suggestions will be great help for me, and Thanks in advance.

If your database tables not gonna change what you can do is create a function select all the data from your local database and pass that data to online function to update your online database with new or updated records.

For ex:

If you have a table called users. From AJAX you will select all local data and create JSON Object pass the data to script function. From that JSON Object you will pass data to online php file and update your online database from it.

Note: You have to careful with giving lot of conditions to check whether data get missing or override.

You'll have to write a service and some code to dump your database (if you want to sync complete database every time) follow this answer

After dumping your sql next you have to upload the file to your server via the service. Upon receiving you can load the data again mysql -u username -p database_name < file.sql

However I won't recommend this, try exploring database approach of Master-Slave Database, where your local server's database will be a Master and your remote server will be slave. Your data will automatically be synchronized.Please see this tutorial

You can implement interface to select tables you want to import in live. Use below code generate CSV files of selected tables and prepare array.

<?php
$file_name_flat = 'TABLE-NAME.csv';  // Replace TABLE-NAME with your selected table name.

$fpointer = fopen(FOLDER-LOCATION.$file_name_flat, 'w+');  // Open CSV file. Replace 
FOLDER-LOCATION with your local folder path where you want to save this CSV files.

//Execute query to get all columns data
$query = "select * FROM TABLE-NAME WHERE 1";  // Replace TABLE-NAME with your selected 
table name. You can set other conditions based on your requirement.

//Execute query as per your CMS / Framework coding standards and write CSV file.
$result_flat = $DB_Connection->query($query)->fetchAll('assoc');
foreach ($result_flat as $fields) {          
  fputcsv($fpointer, $fields);
}

//Prepare Array of CSVs to create ZIP file
$files = array($file_name_flat);

fclose($fpointer); // close CSV file after successfully write.
?>

CREATE ZIP of CSVs

//Create ZIP
$zipname = 'tables_'.date('Y-m-d-H-i-s').'.zip';
createZipFile($files,$zipname,FOLDER_LOCATION);  //Replace FOLDER-LOCATION with your 
local folder path where you saved CSV files. 

/* createZipFile Funcation to create zip file Both params are mandatory */
function createZipFile($files_names = array(),$zipfileName, $files_path=""){

    $zip = new \ZipArchive;
    $zip->open(TMP.$zipfileName, \ZipArchive::CREATE);
    foreach ($files_names as $file) {
        $zip->addFile($files_path.$file,$file);
    }
    $zip->close();

    foreach ($files_names as $file) {
        unlink($files_path.$file);
    }

    ///Then download the zipped file.
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipfileName);
    header('Content-Length: ' . filesize(FOLDER_LOCATION.$zipfileName));
    readfile(TMP.$zipfileName);
    unlink(TMP.$zipfileName);
    die;
}

Now Implement a form to upload this zip file on live server. In Post action of this form add code to get zip file.

$filename = $_FILES['filename']['name'];
$source = $_FILES["filename"]["tmp_name"];

//Upload zip file to server location. Replace SERVER_FOLDER_PATH to server's location 
where you want to save uploaded zip.
if(move_uploaded_file($source, SERVER_FOLDER_PATH)) {

   //Extract ZIP file

    $zip = new \ZipArchive();
    $x = $zip->open($target_path);
    if($x === true) {
       $zip->extractTo(PATH_TO_SAVE_EXTRACTED_ZIP); // change this to the correct site path                    
       $zip->close();

       $cdir = scandir(PATH_TO_SAVE_EXTRACTED_ZIP);  // Read DIR

       $fieldSeparator = ",";
       $lineSeparator = '\n';

       foreach ($cdir as $key => $value)
       {                
          if (!in_array($value,array(".","..")))
          {
             $fileName =  PATH_TO_SAVE_EXTRACTED_ZIP.$value; // replace 
PATH_TO_SAVE_EXTRACTED_ZIP with your server path
             $tableName = SET_TABLE_NAME;  // You have to set the logic to get the table name.

             if (is_file($fileName))  
             {
                 // User MYSQL "LOAD DATA LOCAL INFILE" to IMPORT CSVs into particular tables. There are option available for this LOAD DATA process. It will import your CSV to particular table. No need to execute loop to insert data one by one.

                 $q = 'LOAD DATA LOCAL INFILE "'.$fileName.'"  REPLACE INTO TABLE '.$tableName.' FIELDS TERMINATED BY "' .$fieldSeparator. '" Enclosed BY '.'\'"\''.' LINES TERMINATED BY "'.$lineSeparator.'"';
                 $DB_Connection->query($q);  
         }
      } 
   }
}  

You can check LOAD DATA of MySQL from - MYSQL

您可以在本地计算机上运行cron作业,该作业使用mysqldump导出MySQL数据,然后使用rsync和sshpass将其上传到服务器。

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