18

I was asked to create an export and import mysql database with it's structure and data into a .sql file using php scripting and not phpmyadmin to make the user be able to backup his data?

Does anybody have an idea how to do that??

Thanks in advance

Mohamed Hassan
  • 1,579
  • 4
  • 19
  • 35
  • Does it have to be just PHP? Could always use mysqldump, and if it needed to be a PHP script, could use mysqldump through exec. – Corbin Apr 04 '12 at 22:17
  • 1
    Dup of [Easy way to export a SQL table without access to the server or phpMyADMIN](http://stackoverflow.com/q/81934/), [php code to mysql database export](http://stackoverflow.com/q/2491728/90527), [Best practice: Import mySQL file in PHP; split queries](http://stackoverflow.com/q/1883079/90527), and likely [many others](http://stackoverflow.com/search?q=PHP+MySQL+%2Bexport+%2Bimport). – outis Apr 04 '12 at 22:22

3 Answers3

16

SAFE and WORKING SOLUTION :

EXPORT_TABLES("localhost","user","pass","db_name"); 
// has 5th and 6th optional parameters too.

Latest version is available at github: Export.php + Import.php

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 2
    Thank you! this is a best code. because other codes work with "exec" or "system" functions.this functions disabled on Linux hosts. but this script worked on Linux hosts. – Milad Ghiravani Apr 19 '14 at 22:56
  • Awesome... Thanks for sharing this code Mr.tazo...It's working perfectly for me...Thanks. –  Oct 02 '16 at 12:08
  • fantastic and its very useful one. – Karthi Oct 24 '16 at 06:59
12

http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/using-php-to-backup-mysql-databases.aspx

either

$tableName  = 'mypet';
$backupFile = 'backup/mypet.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysql_query($query);

or

$backupFile = $dbname . date("Y-m-d-H-i-s") . '.gz';
$command = "mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname | gzip >     $backupFile";
system($command);
binarious
  • 4,568
  • 26
  • 35
3

Here is a nice class that worked just fine for me. if it says fopen access denied, try to change the folder permissions.

https://github.com/clouddueling/mysqldump-php

Ayoub
  • 540
  • 5
  • 11