PHP Database Dump Script - are there any issues? - php

I found a PHP function to dump a mySQL database that someone else had written, and then cleaned it up and formatted it a bit. I wanted to know if I could get a critique of it. I have ran it, tested it on a Wordpress blog and the DB completely restores, but wanted to get some other eyes on the code.
Specifically I am looking for feedback on:
Anything that could corrupt the data - not properly escaping etc
Violating any best practice / principles
Security issues
Anything else you may see as an issue
NOTE: I am NOT looking to use mysqldump, I want to completely generate this sql backup from code. I also realize that the filename could be generated randomly, but the SQL file will be uploaded to dropbox as well, and I want to version it under the same name.
Thanks!
Code:
// Variables
$dbHost = 'DBHOST';
$dbUser = 'DBUSER';
$dbPassword = 'DBPASSWORD';
$dbName = 'DBNAME';
$tables = '*';
$fileName = 'mydatabase.sql';
// Logic
$link = #mysql_connect($dbHost, $dbUser, $dbPassword);
$db = #mysql_select_db($dbName, $link);
if(!$link || !$db)
die("Database Error");
//get all of the tables
if($tables == '*') {
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result)) {
$tables[] = $row[0];
}
}
else $tables = is_array($tables) ? $tables : explode(',',$tables);
// Loop through tables
foreach($tables as $table) {
$result = mysql_query('SELECT * FROM '. $table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE IF EXISTS ' . $table . ';';
$createTable = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
$return .= "\n\n" . $createTable[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO ' . $table . ' VALUES(';
for($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace("\n","\\n", $row[$j]);
if (isset($row[$j])) {
$return .= '"' . $row[$j] . '"' ;
}
else {
$return .= '""';
}
if ($j < ($num_fields-1)) {
$return .= ',';
}
}
$return .= ");\n";
}
}
$return .="\n\n\n";
}
// Save the file
$handle = fopen($fileName, 'w+');
fwrite($handle, $return);
fclose($handle);

That script has serious, deal-breaking problems. It will not work for any but the most trivial database.
NULLs are not supported.
Character sets are not taken into account.
Table names are not delimited.
Only tables are supported -- not views, stored procedures, triggers, functions, etc.
addslashes() is not character-set safe.
mysql_query() pre-fetches all the rows from the table, so if you query a table with millions of rows, you will exceed your PHP memory limit. Use mysql_unbuffered_query() instead. On second thought, I see you collect all the output in $return so this is moot.
Your suppression of errors with the # operator is bad practice. Check for errors and fail gracefully with an informative message.
Your requirement not to use mysqldump is absurd.
Why make so much work for yourself reinventing the wheel, and still get it so wrong? Just run mysqldump via shellexec().
See also:
Why is my database backup script not working in php?

Try mysql command or mysqldump command

Character sets? Perhaps SET NAMES utf8 would be a good addition.
Also, what happens if the database contains views?

In case this is a very huge database that needs to be dumped, make sure your server (and php max execution memory per script) has enough memory to keep the whole $return in memory, otherwise you better flush to a file once a while, or every line.

This will not dump stored procedures, functions, views, triggers and so on.
Edit: You can dump procedures etc. this way too. Just use i.e. SHOW PROCEDURE STATUS;
to get the list of procedures and then SHOW CREATE PROCEDURE for each procedure. The same thing for functions, views, triggers...
Don't forget SHOW CREATE DATABASE; either.

create backup DB :
<?php
$dbHost = 'DBHOST';
$dbUser = 'DBUSER';
$dbPassword = 'DBPASSWORD';
$dbName = 'DBNAME';
$tables = '*';
backup_tables($dbHost,$dbUser,$dbPassword,$tables);
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$db = new PDO("mysql:host=$host;dbname=$name;", $user, $pass);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = $db->query('SHOW TABLES');
$tables= $result->fetchAll(PDO::FETCH_COLUMN, 0);
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return="";
//cycle through
foreach($tables as $table)
{
$return.= 'DROP TABLE IF EXISTS '.$table.';';
$result=$db->query('SHOW CREATE TABLE '.$table);
$row2 = $result->fetch(PDO::FETCH_NUM);
$return.= "\n\n".$row2[1].";\n\n";
$result = $db->query('SELECT * FROM '.$table);
foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $key=>$value) {
// build query...
$return .= "INSERT INTO $table (`".implode("`, `", array_keys($value))."`)
VALUES ('".implode("', '", $value)."');\n\n";
}
$return.="\n\n\n";
}
//save file
$handle = fopen('db-backup-'.date('Y-m-d--H-i-s').'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}

Related

Mysqldump database backup through PHP [duplicate]

I don't have a basic understanding of how backup of a MySQL database through PHP would work. I have followed one tutorial but it didn't help me understand.
Can someone explain how to create a MySQL backup from PHP?
While you can execute backup commands from PHP, they don't really have anything to do with PHP. It's all about MySQL.
I'd suggest using the mysqldump utility to back up your database. The documentation can be found here : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html.
The basic usage of mysqldump is
mysqldump -u user_name -p name-of-database >file_to_write_to.sql
You can then restore the backup with a command like
mysql -u user_name -p <file_to_read_from.sql
Do you have access to cron? I'd suggest making a PHP script that runs mysqldump as a cron job. That would be something like
<?php
$filename='database_backup_'.date('G_a_m_d_y').'.sql';
$result=exec('mysqldump database_name --password=your_pass --user=root --single-transaction >/var/backups/'.$filename,$output);
if(empty($output)){/* no output is good */}
else {/* we have something to log the output here*/}
If mysqldump is not available, the article describes another method, using the SELECT INTO OUTFILE and LOAD DATA INFILE commands. The only connection to PHP is that you're using PHP to connect to the database and execute the SQL commands. You could also do this from the command line MySQL program, the MySQL monitor.
It's pretty simple, you're writing an SQL file with one command, and loading/executing it when it's time to restore.
You can find the docs for select into outfile here (just search the page for outfile). LOAD DATA INFILE is essentially the reverse of this. See here for the docs.
Based on the good solution that provided by tazo todua, I've made some of changes since mysql_connect has deprecated and not supported in new php version. I've used mysqli_connect instead and increased the performance of inserting values to the database:
<?php
/**
* Updated: Mohammad M. AlBanna
* Website: MBanna.info
*/
//MySQL server and database
$dbhost = 'localhost';
$dbuser = 'my_user';
$dbpass = 'my_pwd';
$dbname = 'database_name';
$tables = '*';
//Call the core function
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables);
//Core function
function backup_tables($host, $user, $pass, $dbname, $tables = '*') {
$link = mysqli_connect($host,$user,$pass, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($link, "SET NAMES 'utf8'");
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysqli_query($link, 'SHOW TABLES');
while($row = mysqli_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = '';
//cycle through
foreach($tables as $table)
{
$result = mysqli_query($link, 'SELECT * FROM '.$table);
$num_fields = mysqli_num_fields($result);
$num_rows = mysqli_num_rows($result);
$return.= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
$counter = 1;
//Over tables
for ($i = 0; $i < $num_fields; $i++)
{ //Over rows
while($row = mysqli_fetch_row($result))
{
if($counter == 1){
$return.= 'INSERT INTO '.$table.' VALUES(';
} else{
$return.= '(';
}
//Over fields
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
if($num_rows == $counter){
$return.= ");\n";
} else{
$return.= "),\n";
}
++$counter;
}
}
$return.="\n\n\n";
}
//save file
$fileName = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
$handle = fopen($fileName,'w+');
fwrite($handle,$return);
if(fclose($handle)){
echo "Done, the file name is: ".$fileName;
exit;
}
}
If you want to backup a database from php script you could use a class for example lets call it MySQL. This class will use PDO (build in php class which will handle the connection to the database). This class could look like this:
<?php /*defined in your exampleconfig.php*/
define('DBUSER','root');
define('DBPASS','');
define('SERVERHOST','localhost');
?>
<?php /*defined in examplemyclass.php*/
class MySql{
private $dbc;
private $user;
private $pass;
private $dbname;
private $host;
function __construct($host="localhost", $dbname="your_databse_name_here", $user="your_username", $pass="your_password"){
$this->user = $user;
$this->pass = $pass;
$this->dbname = $dbname;
$this->host = $host;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
try{
$this->dbc = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $user, $pass, $opt);
}
catch(PDOException $e){
echo $e->getMessage();
echo "There was a problem with connection to db check credenctials";
}
} /*end function*/
public function backup_tables($tables = '*'){ /* backup the db OR just a table */
$host=$this->host;
$user=$this->user;
$pass=$this->pass;
$dbname=$this->dbname;
$data = "";
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = $this->dbc->prepare('SHOW TABLES');
$result->execute();
while($row = $result->fetch(PDO::FETCH_NUM))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
foreach($tables as $table)
{
$resultcount = $this->dbc->prepare('SELECT count(*) FROM '.$table);
$resultcount->execute();
$num_fields = $resultcount->fetch(PDO::FETCH_NUM);
$num_fields = $num_fields[0];
$result = $this->dbc->prepare('SELECT * FROM '.$table);
$result->execute();
$data.= 'DROP TABLE '.$table.';';
$result2 = $this->dbc->prepare('SHOW CREATE TABLE '.$table);
$result2->execute();
$row2 = $result2->fetch(PDO::FETCH_NUM);
$data.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = $result->fetch(PDO::FETCH_NUM))
{
$data.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $data.= '"'.$row[$j].'"' ; } else { $data.= '""'; }
if ($j<($num_fields-1)) { $data.= ','; }
}
$data.= ");\n";
}
}
$data.="\n\n\n";
}
//save filename
$filename = 'db-backup-'.time().'-'.(implode(",",$tables)).'.sql';
$this->writeUTF8filename($filename,$data);
/*USE EXAMPLE
$connection = new MySql(SERVERHOST,"your_db_name",DBUSER, DBPASS);
$connection->backup_tables(); //OR backup_tables("posts");
$connection->closeConnection();
*/
} /*end function*/
private function writeUTF8filename($filenamename,$content){ /* save as utf8 encoding */
$f=fopen($filenamename,"w+");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$content);
fclose($f);
/*USE EXAMPLE this is only used by public function above...
$this->writeUTF8filename($filename,$data);
*/
} /*end function*/
public function recoverDB($file_to_load){
echo "write some code to load and proccedd .sql file in here ...";
/*USE EXAMPLE this is only used by public function above...
recoverDB("some_buck_up_file.sql");
*/
} /*end function*/
public function closeConnection(){
$this->dbc = null;
//EXAMPLE OF USE
/*$connection->closeConnection();*/
}/*end function*/
} /*END OF CLASS*/
?>
Now you could simply use this in your backup.php:
include ('config.php');
include ('myclass.php');
$connection = new MySql(SERVERHOST,"your_databse_name_here",DBUSER, DBPASS);
$connection->backup_tables(); /*Save all tables and it values in selected database*/
$connection->backup_tables("post_table"); /*Saves only table name posts_table from selected database*/
$connection->closeConnection();
Which means that visiting this page will result in backing up your file... of course it doesn't have to be that way :) you can call this method on every post to your database to be up to date all the time, however, I would recommend to write it to one file at all the time instead of creating new files with time()... as it is above.
Hope it helps and good luck ! :>
Take a look here! It is a native solution written in php. You won't need to exec mysqldump, or cope with incomplete scripts. This is a full mysqldump clone, without dependencies, output compression and sane defaults.
Out of the box, mysqldump-php supports backing up table structures, the data itself, views, triggers and events.
MySQLDump-PHP is the only library that supports:
output binary blobs as hex.
resolves view dependencies (using Stand-In tables).
output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.1 & hhvm)
dumps stored procedures.
dumps events.
does extended-insert and/or complete-insert.
supports virtual columns from MySQL 5.7.
You can install it using composer, or just download the php file, and it is as easy as doing:
use Ifsnop\Mysqldump as IMysqldump;
try {
$dump = new IMysqldump\Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => Mysqldump::NONE,
'init_commands' => array(),
'no-data' => array(),
'reset-auto-increment' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'add-drop-trigger' => true,
'add-locks' => true,
'complete-insert' => false,
'databases' => false,
'default-character-set' => Mysqldump::UTF8,
'disable-keys' => true,
'extended-insert' => true,
'events' => false,
'hex-blob' => true, /* faster than escaped content */
'net_buffer_length' => self::MAXLINESIZE,
'no-autocommit' => true,
'no-create-info' => false,
'lock-tables' => true,
'routines' => false,
'single-transaction' => true,
'skip-triggers' => false,
'skip-tz-utc' => false,
'skip-comments' => false,
'skip-dump-date' => false,
'skip-definer' => false,
'where' => '',
/* deprecated */
'disable-foreign-keys-check' => true
);
An easy way to do this (output SQL file). To do this, we can use exec or mysqli method
code 1:
example 1 : If you want to back-up a specific database
$database = 'YOUR-DB-NAME';
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$dir_1 = dirname(__FILE__) . '/table-'. $database .'.sql';
exec("mysqldump --user={$user} --password={$pass} --host={$host} {$database} --result-file={$dir_1} 2>&1", $output_1);
var_dump($output_1);
example 2 : Backup all database
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$dir_2 = dirname(__FILE__) . '/all-database.sql';
exec("mysqldump --user={$user} --password={$pass} --host={$host} --all-databases --result-file={$dir_2} 2>&1", $output_2);
var_dump($output_2);
example 3 : Backup all database and skip lock tables
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$dir_3 = dirname(__FILE__) . '/skip-lock-tables.sql';
exec("mysqldump --user={$user} --password={$pass} --host={$host} --all-databases --skip-lock-tables --result-file={$dir_3} 2>&1", $output_3);
var_dump($output_3);
I usually use the following code as well to display errors and warning : Not important
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Method 2 If you can not activate exec() function. By Mysqli :
<?php
$database = 'YOUR-DB-NAME';
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$charset = "utf8mb4"; # utf8mb4_unicode_ci
$conn = new mysqli($host, $user, $pass, $database);
$conn->set_charset($charset);
# get all tables
$result = mysqli_query($conn, "SHOW TABLES");
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
# Get tables data
$sqlScript = "";
foreach ($tables as $table) {
$query = "SHOW CREATE TABLE $table";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$sqlScript .= "\n\n" . $row[1] . ";\n\n";
$query = "SELECT * FROM $table";
$result = mysqli_query($conn, $query);
$columnCount = mysqli_num_fields($result);
for ($i = 0; $i < $columnCount; $i ++) {
while ($row = mysqli_fetch_row($result)) {
$sqlScript .= "INSERT INTO $table VALUES(";
for ($j = 0; $j < $columnCount; $j ++) {
$row[$j] = $row[$j];
$sqlScript .= (isset($row[$j])) ? '"' . $row[$j] . '"' : '""';
if ($j < ($columnCount - 1)) {
$sqlScript .= ',';
}
}
$sqlScript .= ");\n";
}
}
$sqlScript .= "\n";
}
//save file
$mysql_file = fopen($database . '_backup_'.time() . '.sql', 'w+');
fwrite($mysql_file ,$sqlScript );
fclose($mysql_file );
From the answer of #DevWL, I got "Undefined offset ..." at
if ($j<($num_fields-1)) { $data.= ','; }
I made some changes to:
preserve relationships (foreign keys)
use Transactions
remove the uneedy $num_fields
class DBbackup {
public $suffix;
public $dirs;
protected $dbInstance;
public function __construct() {
try{
$this->dbInstance = new PDO("mysql:host=".$dbhost.";dbname=".$dbname,
$username, $password);
} catch(Exception $e) {
die("Error ".$e->getMessage());
}
$this->suffix = date('Ymd_His');
}
public function backup($tables = '*'){
$output = "-- database backup - ".date('Y-m-d H:i:s').PHP_EOL;
$output .= "SET NAMES utf8;".PHP_EOL;
$output .= "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';".PHP_EOL;
$output .= "SET foreign_key_checks = 0;".PHP_EOL;
$output .= "SET AUTOCOMMIT = 0;".PHP_EOL;
$output .= "START TRANSACTION;".PHP_EOL;
//get all table names
if($tables == '*') {
$tables = [];
$query = $this->dbInstance->prepare('SHOW TABLES');
$query->execute();
while($row = $query->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
$query->closeCursor();
}
else {
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table) {
$query = $this->dbInstance->prepare("SELECT * FROM `$table`");
$query->execute();
$output .= "DROP TABLE IF EXISTS `$table`;".PHP_EOL;
$query2 = $this->dbInstance->prepare("SHOW CREATE TABLE `$table`");
$query2->execute();
$row2 = $query2->fetch(PDO::FETCH_NUM);
$query2->closeCursor();
$output .= PHP_EOL.$row2[1].";".PHP_EOL;
while($row = $query->fetch(PDO::FETCH_NUM)) {
$output .= "INSERT INTO `$table` VALUES(";
for($j=0; $j<count($row); $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j]))
$output .= "'".$row[$j]."'";
else $output .= "''";
if ($j<(count($row)-1))
$output .= ',';
}
$output .= ");".PHP_EOL;
}
}
$output .= PHP_EOL.PHP_EOL;
$output .= "COMMIT;";
//save filename
$filename = 'db_backup_'.$this->suffix.'.sql';
$this->writeUTF8filename($filename,$output);
}
private function writeUTF8filename($fn,$c){ /* save as utf8 encoding */
$f=fopen($fn,"w+");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$c);
fclose($f);
}
}
And usage example:
$Backup = new DBbackup();
$Backup->backup();
This works great on MySQL 10.1.34-MariaDB , PHP : 7.2.7
A solution to take the backup of your Database in "dbBackup" Folder / Directory
<?php
error_reporting(E_ALL);
/* Define database parameters here */
define("DB_USER", 'root');
define("DB_PASSWORD", 'root');
define("DB_NAME", 'YOUR_DATABASE_NAME');
define("DB_HOST", 'localhost');
define("OUTPUT_DIR", 'dbBackup'); // Folder Path / Directory Name
define("TABLES", '*');
/* Instantiate Backup_Database and perform backup */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "Backup result: " . $status;
/* The Backup_Database class */
class Backup_Database {
private $conn;
/* Constructor initializes database */
function __construct( $host, $username, $passwd, $dbName, $charset = 'utf8' ) {
$this->dbName = $dbName;
$this->connectDatabase( $host, $username, $passwd, $charset );
}
protected function connectDatabase( $host, $username, $passwd, $charset ) {
$this->conn = mysqli_connect( $host, $username, $passwd, $this->dbName);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
/* change character set to $charset Ex : "utf8" */
if (!mysqli_set_charset($this->conn, $charset)) {
printf("Error loading character set ".$charset.": %s\n", mysqli_error($this->conn));
exit();
}
}
/* Backup the whole database or just some tables Use '*' for whole database or 'table1 table2 table3...' #param string $tables */
public function backupTables($tables = '*', $outputDir = '.') {
try {
/* Tables to export */
if ($tables == '*') {
$tables = array();
$result = mysqli_query( $this->conn, 'SHOW TABLES' );
while ( $row = mysqli_fetch_row($result) ) {
$tables[] = $row[0];
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
$sql .= 'USE ' . $this->dbName . ";\n\n";
/* Iterate tables */
foreach ($tables as $table) {
echo "Backing up " . $table . " table...";
$result = mysqli_query( $this->conn, 'SELECT * FROM ' . $table );
// Return the number of fields in result set
$numFields = mysqli_num_fields($result);
$sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysqli_fetch_row( mysqli_query( $this->conn, 'SHOW CREATE TABLE ' . $table ) );
$sql.= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $numFields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$sql .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $numFields; $j++) {
$row[$j] = addslashes($row[$j]);
// $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$sql .= '"' . $row[$j] . '"';
} else {
$sql.= '""';
}
if ($j < ($numFields - 1)) {
$sql .= ',';
}
}
$sql.= ");\n";
}
} // End :: for loop
mysqli_free_result($result); // Free result set
$sql.="\n\n\n";
echo " OK <br/>" . "";
}
} catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return $this->saveFile($sql, $outputDir);
}
/* Save SQL to file #param string $sql */
protected function saveFile(&$sql, $outputDir = '.') {
if (!$sql)
return false;
try {
$handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
fwrite($handle, $sql);
fclose($handle);
mysqli_close( $this->conn );
} catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return true;
}
} // End :: class Backup_Database
?>
for using Cron Job, below is the php function
public function runback() {
$filename = '/var/www/html/local/storage/stores/database_backup_' . date("Y-m-d-H-i-s") . '.sql';
/*
* db backup
*/
$command = "mysqldump --single-transaction -h $dbhost -u$dbuser -p$dbpass yourdb_name > $filename";
system($command);
if ($command == '') {
/* no output is good */
echo 'not done';
} else {
/* we have something to log the output here */
echo 'done';
}
}
There should not be any space between -u and username also no space between -p and password.
CRON JOB command to run this script every sunday 8.30 am:
>> crontab -e
30 8 * * 7 curl -k https://www.websitename.com/takebackup
Try out following example of using SELECT INTO OUTFILE query for creating table backup. This will only backup a particular table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not take data backup: ' . mysql_error());
}
echo "Backedup data successfully\n";
mysql_close($conn);
?>
My very simple backup solution. Each table is saved as a separate file.
<?php
error_reporting(E_ALL);
// set the path to the backup
$bc_dir = dirname(__FILE__).'/back_db/';
// DB-connect settings
$db_user = '';
$db_name = '';
$db_pass = '';
$db_host = 'localhost';
$dsn = 'mysql:dbname='.$db_name.';host='.$db_host.'';
try {
$pdo = new PDO($dsn, $db_user, $db_pass);
} catch (Exception $e) {
var_dump($e->getMessage());
}
$query = $pdo->query('SHOW TABLES');
while ($row = $query->fetch(PDO::FETCH_NUM)) {
exec("mysqldump --user=".$db_user." --password=".$db_pass." --host="
.$db_host." ".$db_name." ".$row[0]." --skip-lock-tables --result-file="
.$bc_dir.$row[0].".sql > /dev/null 2>&1");
}
#T.Todua's answer.
It's cool. However, it failed to backup my database correctly. Hence, I've modified it.
Please use like so: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" );
Thank you.
<?php
/**========================================================+
* +
* Static class with functions for backing up database. +
* +
* PHP Version 5.6.31 +
*=========================================================+*/
class Backup_Mysql_Db
{
private function __construct() {}
/**Initializes the database backup
* #param String $host mysql hostname
* #param String $user mysql user
* #param String $pass mysql password
* #param String $name name of database
* #param String $outputDir the path to the output directory for storing the backup file
* #param Array $tables (optional) to backup specific tables only,like: array("mytable1","mytable2",...)
* #param String $backup_name (optional) backup filename (otherwise, it creates random name)
* EXAMPLE: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" );
*/
public static function init($host,$user,$pass,$name, $outputDir, $tables=false, $backup_name=false)
{
set_time_limit(3000);
$mysqli = new mysqli($host,$user,$pass,$name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//change database to $name
$mysqli->select_db($name);
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8"))
{
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
}
//list all tables in the database
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
//if user opted to backup specific tables only
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
date_default_timezone_set('Africa/Accra');//set your timezone
//$content is the text data to be written to the file for backup
$content = "-- phpMyAdmin SQL Dump\r\n-- version 4.7.4". //insert your phpMyAdmin version
"\r\n-- https://www.phpmyadmin.net/\r\n--\r\n-- Host: ".$host.
"\r\n-- Generation Time: ".date('M d, Y \a\t h:i A',strtotime(date('Y-m-d H:i:s', time()))).
"\r\n-- Server version: ".$mysqli->server_info.
"\r\n-- PHP Version: ". phpversion();
$content .= "\r\n\r\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET AUTOCOMMIT = 0;\r\nSTART TRANSACTION;\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;\r\n/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;\r\n/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8mb4 */;\r\n\r\n--\r\n-- Database: `".
$name."`\r\n--\r\nCREATE DATABASE IF NOT EXISTS `".
$name."` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;\r\nUSE `".
$name."`;";
//traverse through every table in the database
foreach($target_tables as $table)
{
if (empty($table)){ continue; }
$result = $mysqli->query('SELECT * FROM `'.$table.'`');
//get the number of columns
$fields_amount=$result->field_count;
//get the number of affected rows in the MySQL operation
$rows_num=$mysqli->affected_rows;
//Retrieve the Table Definition of the existing table
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine=$res->fetch_row();
$content .= "\r\n\r\n-- --------------------------------------------------------\r\n\r\n"."--\r\n-- Table structure for table `".$table."`\r\n--\r\n\r\n";
//if the table is not empty
if(!self::table_is_empty($table,$mysqli))
{ $content .= $TableMLine[1].";\n\n";//append the Table Definition
//replace, case insensitively
$content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
"DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
$content);//in this
$content .= "--\r\n-- Dumping data for table `".$table."`\r\n--\r\n";
$content .= "\nINSERT INTO `".$table."` (".self::get_columns_from_table($table, $mysqli)." ) VALUES\r\n".self::get_values_from_table($table,$mysqli);
}
else//otherwise if the table is empty
{
$content .= $TableMLine[1].";";
//replace, case insensitively
$content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
"DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
$content);//in this
}
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;";
date_default_timezone_set('Africa/Accra');
//format the time at this very moment and get rid of the colon ( windows doesn't allow colons in filenames)
$date = str_replace(":", "-", date('jS M, y. h:i:s A.',strtotime(date('Y-m-d H:i:s', time()))));
//if there's a backup name, use it , otherwise device one
$backup_name = $backup_name ? $backup_name : $name.'___('.$date.').sql';
//Get current buffer contents and delete current output buffer
ob_get_clean();
self::saveFile($content, $backup_name, $outputDir);
exit;
}
/** Save data to file.
* #param String $data The text data to be stored in the file
* #param String $backup_name The name of the backup file
* #param String $outputDir (optional) The directory to save the file to.
* If unspecified, will save in the current directory.
* */
private static function saveFile(&$data,$backup_name, $outputDir = '.')
{
if (!$data)
{
return false;
}
try
{
$handle = fopen($outputDir . '/'. $backup_name , 'w+');
fwrite($handle, $data);
fclose($handle);
} catch (Exception $e)
{
var_dump($e->getMessage());
return false;
}
return true;
}
/**Checks if table is empty
* #param String $table table in mysql database
* #return Boolean true if table is empty, false otherwise
*/
private static function table_is_empty($table,$mysqli)
{
$sql = "SELECT * FROM $table";
$result = mysqli_query($mysqli, $sql);
if($result)
{
if(mysqli_num_rows($result) > 0)
{
return false;
}
else
{
return true;
}
}
return false;
}
/**Retrieves the columns in the table
* #param String $table table in mysql database
* #return String a list of all the columns in the right format
*/
private static function get_columns_from_table($table, $mysqli)
{
$column_header = "";
$result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");
while($row = $result->fetch_row())
{
$column_header .= "`".$row[0]."`, ";
}
//remove leading and trailing whitespace, and remove the last comma in the string
return rtrim(trim($column_header),',');
}
/**Retrieves the values in the table row by row in the table
* #param String $table table in mysql database
* #return String a list of all the values in the table in the right format
*/
private static function get_values_from_table($table, $mysqli)
{
$values = "";
$columns = [];
//get all the columns in the table
$result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");
while($row = $result->fetch_row())
{
array_push($columns,$row[0] );
}
$result1 = mysqli_query($mysqli, "SELECT * FROM $table");
//while traversing every row in the table(row by row)
while($row = mysqli_fetch_array($result1))
{ $values .= "(";
//get the values in each column
foreach($columns as $col)
{ //if the value is an Integer
$values .= (self::column_is_of_int_type($table, $col,$mysqli)?
$row["$col"].", "://do not surround it with single quotes
"'".$row["$col"]."', "); //otherwise, surround it with single quotes
}
$values = rtrim(trim($values),','). "),\r\n";
}
return rtrim(trim($values),',').";";
}
/**Checks if the data type in the column is an integer
* #param String $table table in mysql database
* #return Boolean true if it is an integer, false otherwise.
*/
private static function column_is_of_int_type($table, $column,$mysqli)
{
$q = mysqli_query($mysqli,"DESCRIBE $table");
while($row = mysqli_fetch_array($q))
{
if ($column === "{$row['Field']}")
{
if (strpos("{$row['Type']}", 'int') !== false)
{
return true;
}
}
}
return false;
}
}

How do I import a .sql file in mysql database using PHP?

I'm trying to import a .sql file through PHP code. However, my code shows this error:
There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:
MySQL Database Name: test
MySQL User Name: root
MySQL Password: NOTSHOWN
MySQL Host Name: localhost
MySQL Import Filename: dbbackupmember.sql
And this is my code:
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
exec($command,$output=array(),$worked);
switch($worked){
case 0:
echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
break;
case 1:
echo 'There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:<br/><br/><table><tr><td>MySQL Database Name:</td><td><b>' .$mysqlDatabaseName .'</b></td></tr><tr><td>MySQL User Name:</td><td><b>' .$mysqlUserName .'</b></td></tr><tr><td>MySQL Password:</td><td><b>NOTSHOWN</b></td></tr><tr><td>MySQL Host Name:</td><td><b>' .$mysqlHostName .'</b></td></tr><tr><td>MySQL Import Filename:</td><td><b>' .$mysqlImportFilename .'</b></td></tr></table>';
break;
}
?>
What am I doing wrong? The SQL file is in the same directory.
Warning: mysql_* extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.
I have got another way to do this, try this
<?php
// Name of the file
$filename = 'churc.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '';
// Database name
$mysql_database = 'dump';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>
This is working for me
You can use the mysqli multi_query function as below:
$sql = file_get_contents('mysqldump.sql');
$mysqli = new mysqli("localhost", "root", "pass", "testdb");
/* execute multi query */
$mysqli->multi_query($sql);
Warning: mysql_* extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.
the answer from Raj is useful, but (because of file($filename))
it will fail if your mysql-dump not fits in memory
If you are on shared hosting and there are limitations like 30 MB and 12s Script runtime and you have to restore a x00MB mysql dump, you can use this script:
it will walk the dumpfile query for query, if the script execution deadline is near, it saves the current fileposition in a tmp file and a automatic browser reload will continue this process again and again ...
If an error occurs, the reload will stop and an the error is shown ...
if you comeback from lunch your db will be restored ;-)
the noLimitDumpRestore.php:
// your config
$filename = 'yourGigaByteDump.sql';
$dbHost = 'localhost';
$dbUser = 'user';
$dbPass = '__pass__';
$dbName = 'dbname';
$maxRuntime = 8; // less then your max script execution limit
$deadline = time()+$maxRuntime;
$progressFilename = $filename.'_filepointer'; // tmp file for progress
$errorFilename = $filename.'_error'; // tmp file for erro
mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());
($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);
// check for previous error
if( file_exists($errorFilename) ){
die('<pre> previous error: '.file_get_contents($errorFilename));
}
// activate automatic reload in browser
echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';
// go to previous file position
$filePosition = 0;
if( file_exists($progressFilename) ){
$filePosition = file_get_contents($progressFilename);
fseek($fp, $filePosition);
}
$queryCount = 0;
$query = '';
while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
if(substr($line,0,2)=='--' OR trim($line)=='' ){
continue;
}
$query .= $line;
if( substr(trim($query),-1)==';' ){
if( !mysql_query($query) ){
$error = 'Error performing query \'<strong>' . $query . '\': ' . mysql_error();
file_put_contents($errorFilename, $error."\n");
exit;
}
$query = '';
file_put_contents($progressFilename, ftell($fp)); // save the current file position for
$queryCount++;
}
}
if( feof($fp) ){
echo 'dump successfully restored!';
}else{
echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
}
<?php
$host = "localhost";
$uname = "root";
$pass = "";
$database = "demo1"; //Change Your Database Name
$conn = new mysqli($host, $uname, $pass, $database);
$filename = 'users.sql'; //How to Create SQL File Step : url:http://localhost/phpmyadmin->detabase select->table select->Export(In Upper Toolbar)->Go:DOWNLOAD .SQL FILE
$op_data = '';
$lines = file($filename);
foreach ($lines as $line)
{
if (substr($line, 0, 2) == '--' || $line == '')//This IF Remove Comment Inside SQL FILE
{
continue;
}
$op_data .= $line;
if (substr(trim($line), -1, 1) == ';')//Breack Line Upto ';' NEW QUERY
{
$conn->query($op_data);
$op_data = '';
}
}
echo "Table Created Inside " . $database . " Database.......";
?>
<?php
system('mysql --user=USER --password=PASSWORD DATABASE< FOLDER/.sql');
?>
Grain Script is superb and save my day. Meanwhile mysql is depreciated and I rewrote Grain answer using PDO.
$server = 'localhost';
$username = 'root';
$password = 'your password';
$database = 'sample_db';
/* PDO connection start */
$conn = new PDO("mysql:host=$server; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
/* PDO connection end */
// your config
$filename = 'yourFile.sql';
$maxRuntime = 8; // less then your max script execution limit
$deadline = time()+$maxRuntime;
$progressFilename = $filename.'_filepointer'; // tmp file for progress
$errorFilename = $filename.'_error'; // tmp file for erro
($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);
// check for previous error
if( file_exists($errorFilename) ){
die('<pre> previous error: '.file_get_contents($errorFilename));
}
// activate automatic reload in browser
echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';
// go to previous file position
$filePosition = 0;
if( file_exists($progressFilename) ){
$filePosition = file_get_contents($progressFilename);
fseek($fp, $filePosition);
}
$queryCount = 0;
$query = '';
while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
if(substr($line,0,2)=='--' OR trim($line)=='' ){
continue;
}
$query .= $line;
if( substr(trim($query),-1)==';' ){
$igweze_prep= $conn->prepare($query);
if(!($igweze_prep->execute())){
$error = 'Error performing query \'<strong>' . $query . '\': ' . print_r($conn->errorInfo());
file_put_contents($errorFilename, $error."\n");
exit;
}
$query = '';
file_put_contents($progressFilename, ftell($fp)); // save the current file position for
$queryCount++;
}
}
if( feof($fp) ){
echo 'dump successfully restored!';
}else{
echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
}
I have Test your code, this error shows when you already have the DB imported or with some tables with the same name, also the Array error that shows is because you add in in the exec parenthesis, here is the fixed version:
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
$output=array();
exec($command,$output,$worked);
switch($worked){
case 0:
echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
break;
case 1:
echo 'There was an error during import.';
break;
}
?>
If you need a User Interface and if you want to use PDO
Here's a simple solution
<form method="post" enctype="multipart/form-data">
<input type="text" name="db" placeholder="Databasename" />
<input type="file" name="file">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])){
$query = file_get_contents($_FILES["file"]["name"]);
$dbname = $_POST['db'];
$con = new PDO("mysql:host=localhost;dbname=$dbname","root","");
$stmt = $con->prepare($query);
if($stmt->execute()){
echo "Successfully imported to the $dbname.";
}
}
?>
Definitely working on my end. Worth a try.
If you are using PHP version 7 or higher, try below script,
// Name of the file
$filename = 'sql.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'username';
// MySQL password
$mysql_password = 'password';
// Database name
$mysql_database = 'database';
// Connect to MySQL server
$con = #new mysqli($mysql_host,$mysql_username,$mysql_password,$mysql_database);
// Check connection
if ($con->connect_errno) {
echo "Failed to connect to MySQL: " . $con->connect_errno;
echo "<br/>Error: " . $con->connect_error;
}
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line) {
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
// Perform the query
$con->query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . $con->error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
$con->close($con);
// Import data
$filename = 'database_file_name.sql';
import_tables('localhost','root','','database_name',$filename);
function import_tables($host,$uname,$pass,$database, $filename,$tables = '*'){
$connection = mysqli_connect($host,$uname,$pass)
or die("Database Connection Failed");
$selectdb = mysqli_select_db($connection, $database) or die("Database could not be selected");
$templine = '';
$lines = file($filename); // Read entire file
foreach ($lines as $line){
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*' )
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
mysqli_query($connection, $templine)
or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
$templine = '';
}
}
echo "Tables imported successfully";
}
// Backup database from php script
backup_tables('hostname','UserName','pass','databses_name');
function backup_tables($host,$user,$pass,$name,$tables = '*'){
$link = mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($link,$name);
//get all of the tables
if($tables == '*'){
$tables = array();
$result = mysqli_query($link,'SHOW TABLES');
while($row = mysqli_fetch_row($result))
{
$tables[] = $row[0];
}
}else{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = '';
foreach($tables as $table)
{
$result = mysqli_query($link,'SELECT * FROM '.$table);
$num_fields = mysqli_num_fields($result);
$row_query = mysqli_query($link,'SHOW CREATE TABLE '.$table);
$row2 = mysqli_fetch_row($row_query);
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysqli_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j < $num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", '\n', $row[$j]);
if (isset($row[$j])) {
$return.= '"'.$row[$j].'"' ;
} else {
$return.= '""';
}
if ($j < ($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
//save file
$handle = fopen('backup-'.date("d_m_Y__h_i_s_A").'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
I recommend an old but still working tool bigdump
I use this code and RUN SUCCESS FULL:
$filename = 'apptoko-2016-12-23.sql'; //change to ur .sql file
$handle = fopen($filename, "r+");
$contents = fread($handle, filesize($filename));
$sql = explode(";",$contents);//
foreach($sql as $query){
$result=mysql_query($query);
if ($result){
echo '<tr><td><BR></td></tr>';
echo '<tr><td>' . $query . ' <b>SUCCESS</b></td></tr>';
echo '<tr><td><BR></td></tr>';
}
}
fclose($handle);
Solution special chars
$link=mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());
//charset important
mysql_set_charset('utf8',$link);
I Thing you can Try this Code, It's Run for my Case:
<?php
$con = mysqli_connect('localhost', 'root', 'NOTSHOWN', 'test');
$filename = 'dbbackupmember.sql';
$handle = fopen($filename, 'r+');
$contents = fread($handle, filesize($filename));
$sql = explode(";", $contents);
foreach ($sql as $query) {
$result = mysqli_query($con, $query);
if ($result) {
echo "<tr><td><br></td></tr>";
echo "<tr><td>".$query."</td></tr>";
echo "<tr><td><br></td></tr>";
}
}
fclose($handle);
echo "success";
?>
function restoreDatabase($db_name,$file_path)
{
//checking valid extension file
$path_parts = pathinfo($file_path);
$ext_file = $path_parts['extension'];
$filename = $path_parts['basename'];
if($ext_file == "sql")
{
$c = new Config();
$confJson = $c->getConfig();
$conf = json_decode($confJson);
$dbhost = "127.0.0.1";
$dbuser = $conf->db_username;
$dbpwd = $conf->db_password;
$dbname = $db_name;
$dumpfile = $file_path;
$is_file = file_exists($file_path);
if($is_file == TRUE)
{
//passthru("/usr/bin/mysqldump --opt --host=$dbhost --user=$dbuser --password=$dbpwd $dbname < $dumpfile");
//passthru("tail -1 $dumpfile");
system('mysql --user='.$dbuser.' --password='.$dbpwd.' '.$db_name.' < '.$file_path);
return "Database was restored from $filename ";
}
else
{
return "Restore database was aborted due ".$filename." does not exist!";
}
}
else
{
return "Invalid file format.Require sql file to restore this ".$db_name." database. ".$filename." is not sql file format\n(eg. mybackupfile.sql).";
}
}
As we all know MySQL was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 ref so I have converted accepted answer to mysqli.
<?php
// Name of the file
$filename = 'db.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '123456';
// Database name
$mysql_database = 'mydb';
$connection = mysqli_connect($mysql_host,$mysql_username,$mysql_password,$mysql_database) or die(mysqli_error($connection));
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysqli_query($connection,$templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>

PHP XML parsing issue

I want to be able to parse a SQL database with PHP to output an XML, however I cannot get it to show the table name and all of it's contents. I could use some help, here is my code without login information:
I have defined the db server,mdb user and pass, and db name; should anything else be defined?
<?php
// connection to the database
$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die("Unable to connect to MySQL");
// select a database to work with
$selected = mysql_select_db(DB_NAME, $dbhandle)
or die("Could not select data");
// return all available tables
$result_tbl = mysql_query( "SHOW TABLES FROM "DB_NAME, $dbhandle );
$tables = array();
while ($row = mysql_fetch_row($result_tbl)) {
$tables[] = $row[0];
}
$output = "<?xml version=\"1.0\" ?>\n";
$output .= "<schema>";
// iterate over each table and return the fields for each table
foreach ( $tables as $table ) {
$output .= "<table name=\"$table\">";
$result_fld = mysql_query( "SHOW FIELDS FROM "$table, $dbhandle );
while( $row1 = mysql_fetch_row($result_fld) ) {
$output .= "<field name=\"$row1[0]\" type=\"$row1[1]\"";
$output .= ($row1[3] == "PRI") ? " primary_key=\"yes\" />" : " />";
}
$output .= "</table>";
}
$output .= "</schema>";
// tell the browser what kind of file is come in
header("Content-type: text/xml");
// print out XML that describes the schema
echo $output;
// close the connection
mysql_close($dbhandle);
?>
I think it's better to use standard php class XmlWriter for this one.
Look at http://www.php.net/manual/en/book.xmlwriter.php
$result_tbl = mysql_query( "SHOW TABLES FROM "DB_NAME, $dbhandle );
^^^---typo
$result_fld = mysql_query( "SHOW FIELDS FROM "$table, $dbhandle );
^^^---typo
You've got at least two typos in your queries. Most likely you want this:
$result_tbl = mysql_query("SHOW TABLES FROM " . DB_NAME, $dbhandle) or die(mysql_error());
and
$result_fld = mysql_query("SHOW FIELDS FROM $table", $dbhandle) or die(mysql_error());
Note the concatenation operator (.) on the first one, and the addition of or die(...). Never assume a query succeeds. even if the query string itself is syntactically correct, there's far too many OTHER reasons is could fail to NOT check for an error condition.

How to backup MySQL database in PHP?

I don't have a basic understanding of how backup of a MySQL database through PHP would work. I have followed one tutorial but it didn't help me understand.
Can someone explain how to create a MySQL backup from PHP?
While you can execute backup commands from PHP, they don't really have anything to do with PHP. It's all about MySQL.
I'd suggest using the mysqldump utility to back up your database. The documentation can be found here : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html.
The basic usage of mysqldump is
mysqldump -u user_name -p name-of-database >file_to_write_to.sql
You can then restore the backup with a command like
mysql -u user_name -p <file_to_read_from.sql
Do you have access to cron? I'd suggest making a PHP script that runs mysqldump as a cron job. That would be something like
<?php
$filename='database_backup_'.date('G_a_m_d_y').'.sql';
$result=exec('mysqldump database_name --password=your_pass --user=root --single-transaction >/var/backups/'.$filename,$output);
if(empty($output)){/* no output is good */}
else {/* we have something to log the output here*/}
If mysqldump is not available, the article describes another method, using the SELECT INTO OUTFILE and LOAD DATA INFILE commands. The only connection to PHP is that you're using PHP to connect to the database and execute the SQL commands. You could also do this from the command line MySQL program, the MySQL monitor.
It's pretty simple, you're writing an SQL file with one command, and loading/executing it when it's time to restore.
You can find the docs for select into outfile here (just search the page for outfile). LOAD DATA INFILE is essentially the reverse of this. See here for the docs.
Based on the good solution that provided by tazo todua, I've made some of changes since mysql_connect has deprecated and not supported in new php version. I've used mysqli_connect instead and increased the performance of inserting values to the database:
<?php
/**
* Updated: Mohammad M. AlBanna
* Website: MBanna.info
*/
//MySQL server and database
$dbhost = 'localhost';
$dbuser = 'my_user';
$dbpass = 'my_pwd';
$dbname = 'database_name';
$tables = '*';
//Call the core function
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables);
//Core function
function backup_tables($host, $user, $pass, $dbname, $tables = '*') {
$link = mysqli_connect($host,$user,$pass, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($link, "SET NAMES 'utf8'");
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysqli_query($link, 'SHOW TABLES');
while($row = mysqli_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = '';
//cycle through
foreach($tables as $table)
{
$result = mysqli_query($link, 'SELECT * FROM '.$table);
$num_fields = mysqli_num_fields($result);
$num_rows = mysqli_num_rows($result);
$return.= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
$counter = 1;
//Over tables
for ($i = 0; $i < $num_fields; $i++)
{ //Over rows
while($row = mysqli_fetch_row($result))
{
if($counter == 1){
$return.= 'INSERT INTO '.$table.' VALUES(';
} else{
$return.= '(';
}
//Over fields
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
if($num_rows == $counter){
$return.= ");\n";
} else{
$return.= "),\n";
}
++$counter;
}
}
$return.="\n\n\n";
}
//save file
$fileName = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
$handle = fopen($fileName,'w+');
fwrite($handle,$return);
if(fclose($handle)){
echo "Done, the file name is: ".$fileName;
exit;
}
}
If you want to backup a database from php script you could use a class for example lets call it MySQL. This class will use PDO (build in php class which will handle the connection to the database). This class could look like this:
<?php /*defined in your exampleconfig.php*/
define('DBUSER','root');
define('DBPASS','');
define('SERVERHOST','localhost');
?>
<?php /*defined in examplemyclass.php*/
class MySql{
private $dbc;
private $user;
private $pass;
private $dbname;
private $host;
function __construct($host="localhost", $dbname="your_databse_name_here", $user="your_username", $pass="your_password"){
$this->user = $user;
$this->pass = $pass;
$this->dbname = $dbname;
$this->host = $host;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
try{
$this->dbc = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $user, $pass, $opt);
}
catch(PDOException $e){
echo $e->getMessage();
echo "There was a problem with connection to db check credenctials";
}
} /*end function*/
public function backup_tables($tables = '*'){ /* backup the db OR just a table */
$host=$this->host;
$user=$this->user;
$pass=$this->pass;
$dbname=$this->dbname;
$data = "";
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = $this->dbc->prepare('SHOW TABLES');
$result->execute();
while($row = $result->fetch(PDO::FETCH_NUM))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
foreach($tables as $table)
{
$resultcount = $this->dbc->prepare('SELECT count(*) FROM '.$table);
$resultcount->execute();
$num_fields = $resultcount->fetch(PDO::FETCH_NUM);
$num_fields = $num_fields[0];
$result = $this->dbc->prepare('SELECT * FROM '.$table);
$result->execute();
$data.= 'DROP TABLE '.$table.';';
$result2 = $this->dbc->prepare('SHOW CREATE TABLE '.$table);
$result2->execute();
$row2 = $result2->fetch(PDO::FETCH_NUM);
$data.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = $result->fetch(PDO::FETCH_NUM))
{
$data.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $data.= '"'.$row[$j].'"' ; } else { $data.= '""'; }
if ($j<($num_fields-1)) { $data.= ','; }
}
$data.= ");\n";
}
}
$data.="\n\n\n";
}
//save filename
$filename = 'db-backup-'.time().'-'.(implode(",",$tables)).'.sql';
$this->writeUTF8filename($filename,$data);
/*USE EXAMPLE
$connection = new MySql(SERVERHOST,"your_db_name",DBUSER, DBPASS);
$connection->backup_tables(); //OR backup_tables("posts");
$connection->closeConnection();
*/
} /*end function*/
private function writeUTF8filename($filenamename,$content){ /* save as utf8 encoding */
$f=fopen($filenamename,"w+");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$content);
fclose($f);
/*USE EXAMPLE this is only used by public function above...
$this->writeUTF8filename($filename,$data);
*/
} /*end function*/
public function recoverDB($file_to_load){
echo "write some code to load and proccedd .sql file in here ...";
/*USE EXAMPLE this is only used by public function above...
recoverDB("some_buck_up_file.sql");
*/
} /*end function*/
public function closeConnection(){
$this->dbc = null;
//EXAMPLE OF USE
/*$connection->closeConnection();*/
}/*end function*/
} /*END OF CLASS*/
?>
Now you could simply use this in your backup.php:
include ('config.php');
include ('myclass.php');
$connection = new MySql(SERVERHOST,"your_databse_name_here",DBUSER, DBPASS);
$connection->backup_tables(); /*Save all tables and it values in selected database*/
$connection->backup_tables("post_table"); /*Saves only table name posts_table from selected database*/
$connection->closeConnection();
Which means that visiting this page will result in backing up your file... of course it doesn't have to be that way :) you can call this method on every post to your database to be up to date all the time, however, I would recommend to write it to one file at all the time instead of creating new files with time()... as it is above.
Hope it helps and good luck ! :>
Take a look here! It is a native solution written in php. You won't need to exec mysqldump, or cope with incomplete scripts. This is a full mysqldump clone, without dependencies, output compression and sane defaults.
Out of the box, mysqldump-php supports backing up table structures, the data itself, views, triggers and events.
MySQLDump-PHP is the only library that supports:
output binary blobs as hex.
resolves view dependencies (using Stand-In tables).
output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.1 & hhvm)
dumps stored procedures.
dumps events.
does extended-insert and/or complete-insert.
supports virtual columns from MySQL 5.7.
You can install it using composer, or just download the php file, and it is as easy as doing:
use Ifsnop\Mysqldump as IMysqldump;
try {
$dump = new IMysqldump\Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => Mysqldump::NONE,
'init_commands' => array(),
'no-data' => array(),
'reset-auto-increment' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'add-drop-trigger' => true,
'add-locks' => true,
'complete-insert' => false,
'databases' => false,
'default-character-set' => Mysqldump::UTF8,
'disable-keys' => true,
'extended-insert' => true,
'events' => false,
'hex-blob' => true, /* faster than escaped content */
'net_buffer_length' => self::MAXLINESIZE,
'no-autocommit' => true,
'no-create-info' => false,
'lock-tables' => true,
'routines' => false,
'single-transaction' => true,
'skip-triggers' => false,
'skip-tz-utc' => false,
'skip-comments' => false,
'skip-dump-date' => false,
'skip-definer' => false,
'where' => '',
/* deprecated */
'disable-foreign-keys-check' => true
);
An easy way to do this (output SQL file). To do this, we can use exec or mysqli method
code 1:
example 1 : If you want to back-up a specific database
$database = 'YOUR-DB-NAME';
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$dir_1 = dirname(__FILE__) . '/table-'. $database .'.sql';
exec("mysqldump --user={$user} --password={$pass} --host={$host} {$database} --result-file={$dir_1} 2>&1", $output_1);
var_dump($output_1);
example 2 : Backup all database
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$dir_2 = dirname(__FILE__) . '/all-database.sql';
exec("mysqldump --user={$user} --password={$pass} --host={$host} --all-databases --result-file={$dir_2} 2>&1", $output_2);
var_dump($output_2);
example 3 : Backup all database and skip lock tables
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$dir_3 = dirname(__FILE__) . '/skip-lock-tables.sql';
exec("mysqldump --user={$user} --password={$pass} --host={$host} --all-databases --skip-lock-tables --result-file={$dir_3} 2>&1", $output_3);
var_dump($output_3);
I usually use the following code as well to display errors and warning : Not important
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Method 2 If you can not activate exec() function. By Mysqli :
<?php
$database = 'YOUR-DB-NAME';
$user = 'USERNAME';
$pass = 'PASSWORD';
$host = 'localhost';
$charset = "utf8mb4"; # utf8mb4_unicode_ci
$conn = new mysqli($host, $user, $pass, $database);
$conn->set_charset($charset);
# get all tables
$result = mysqli_query($conn, "SHOW TABLES");
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
# Get tables data
$sqlScript = "";
foreach ($tables as $table) {
$query = "SHOW CREATE TABLE $table";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$sqlScript .= "\n\n" . $row[1] . ";\n\n";
$query = "SELECT * FROM $table";
$result = mysqli_query($conn, $query);
$columnCount = mysqli_num_fields($result);
for ($i = 0; $i < $columnCount; $i ++) {
while ($row = mysqli_fetch_row($result)) {
$sqlScript .= "INSERT INTO $table VALUES(";
for ($j = 0; $j < $columnCount; $j ++) {
$row[$j] = $row[$j];
$sqlScript .= (isset($row[$j])) ? '"' . $row[$j] . '"' : '""';
if ($j < ($columnCount - 1)) {
$sqlScript .= ',';
}
}
$sqlScript .= ");\n";
}
}
$sqlScript .= "\n";
}
//save file
$mysql_file = fopen($database . '_backup_'.time() . '.sql', 'w+');
fwrite($mysql_file ,$sqlScript );
fclose($mysql_file );
From the answer of #DevWL, I got "Undefined offset ..." at
if ($j<($num_fields-1)) { $data.= ','; }
I made some changes to:
preserve relationships (foreign keys)
use Transactions
remove the uneedy $num_fields
class DBbackup {
public $suffix;
public $dirs;
protected $dbInstance;
public function __construct() {
try{
$this->dbInstance = new PDO("mysql:host=".$dbhost.";dbname=".$dbname,
$username, $password);
} catch(Exception $e) {
die("Error ".$e->getMessage());
}
$this->suffix = date('Ymd_His');
}
public function backup($tables = '*'){
$output = "-- database backup - ".date('Y-m-d H:i:s').PHP_EOL;
$output .= "SET NAMES utf8;".PHP_EOL;
$output .= "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';".PHP_EOL;
$output .= "SET foreign_key_checks = 0;".PHP_EOL;
$output .= "SET AUTOCOMMIT = 0;".PHP_EOL;
$output .= "START TRANSACTION;".PHP_EOL;
//get all table names
if($tables == '*') {
$tables = [];
$query = $this->dbInstance->prepare('SHOW TABLES');
$query->execute();
while($row = $query->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
$query->closeCursor();
}
else {
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table) {
$query = $this->dbInstance->prepare("SELECT * FROM `$table`");
$query->execute();
$output .= "DROP TABLE IF EXISTS `$table`;".PHP_EOL;
$query2 = $this->dbInstance->prepare("SHOW CREATE TABLE `$table`");
$query2->execute();
$row2 = $query2->fetch(PDO::FETCH_NUM);
$query2->closeCursor();
$output .= PHP_EOL.$row2[1].";".PHP_EOL;
while($row = $query->fetch(PDO::FETCH_NUM)) {
$output .= "INSERT INTO `$table` VALUES(";
for($j=0; $j<count($row); $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j]))
$output .= "'".$row[$j]."'";
else $output .= "''";
if ($j<(count($row)-1))
$output .= ',';
}
$output .= ");".PHP_EOL;
}
}
$output .= PHP_EOL.PHP_EOL;
$output .= "COMMIT;";
//save filename
$filename = 'db_backup_'.$this->suffix.'.sql';
$this->writeUTF8filename($filename,$output);
}
private function writeUTF8filename($fn,$c){ /* save as utf8 encoding */
$f=fopen($fn,"w+");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$c);
fclose($f);
}
}
And usage example:
$Backup = new DBbackup();
$Backup->backup();
This works great on MySQL 10.1.34-MariaDB , PHP : 7.2.7
A solution to take the backup of your Database in "dbBackup" Folder / Directory
<?php
error_reporting(E_ALL);
/* Define database parameters here */
define("DB_USER", 'root');
define("DB_PASSWORD", 'root');
define("DB_NAME", 'YOUR_DATABASE_NAME');
define("DB_HOST", 'localhost');
define("OUTPUT_DIR", 'dbBackup'); // Folder Path / Directory Name
define("TABLES", '*');
/* Instantiate Backup_Database and perform backup */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "Backup result: " . $status;
/* The Backup_Database class */
class Backup_Database {
private $conn;
/* Constructor initializes database */
function __construct( $host, $username, $passwd, $dbName, $charset = 'utf8' ) {
$this->dbName = $dbName;
$this->connectDatabase( $host, $username, $passwd, $charset );
}
protected function connectDatabase( $host, $username, $passwd, $charset ) {
$this->conn = mysqli_connect( $host, $username, $passwd, $this->dbName);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
/* change character set to $charset Ex : "utf8" */
if (!mysqli_set_charset($this->conn, $charset)) {
printf("Error loading character set ".$charset.": %s\n", mysqli_error($this->conn));
exit();
}
}
/* Backup the whole database or just some tables Use '*' for whole database or 'table1 table2 table3...' #param string $tables */
public function backupTables($tables = '*', $outputDir = '.') {
try {
/* Tables to export */
if ($tables == '*') {
$tables = array();
$result = mysqli_query( $this->conn, 'SHOW TABLES' );
while ( $row = mysqli_fetch_row($result) ) {
$tables[] = $row[0];
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
$sql .= 'USE ' . $this->dbName . ";\n\n";
/* Iterate tables */
foreach ($tables as $table) {
echo "Backing up " . $table . " table...";
$result = mysqli_query( $this->conn, 'SELECT * FROM ' . $table );
// Return the number of fields in result set
$numFields = mysqli_num_fields($result);
$sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysqli_fetch_row( mysqli_query( $this->conn, 'SHOW CREATE TABLE ' . $table ) );
$sql.= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $numFields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$sql .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $numFields; $j++) {
$row[$j] = addslashes($row[$j]);
// $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$sql .= '"' . $row[$j] . '"';
} else {
$sql.= '""';
}
if ($j < ($numFields - 1)) {
$sql .= ',';
}
}
$sql.= ");\n";
}
} // End :: for loop
mysqli_free_result($result); // Free result set
$sql.="\n\n\n";
echo " OK <br/>" . "";
}
} catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return $this->saveFile($sql, $outputDir);
}
/* Save SQL to file #param string $sql */
protected function saveFile(&$sql, $outputDir = '.') {
if (!$sql)
return false;
try {
$handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
fwrite($handle, $sql);
fclose($handle);
mysqli_close( $this->conn );
} catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return true;
}
} // End :: class Backup_Database
?>
for using Cron Job, below is the php function
public function runback() {
$filename = '/var/www/html/local/storage/stores/database_backup_' . date("Y-m-d-H-i-s") . '.sql';
/*
* db backup
*/
$command = "mysqldump --single-transaction -h $dbhost -u$dbuser -p$dbpass yourdb_name > $filename";
system($command);
if ($command == '') {
/* no output is good */
echo 'not done';
} else {
/* we have something to log the output here */
echo 'done';
}
}
There should not be any space between -u and username also no space between -p and password.
CRON JOB command to run this script every sunday 8.30 am:
>> crontab -e
30 8 * * 7 curl -k https://www.websitename.com/takebackup
Try out following example of using SELECT INTO OUTFILE query for creating table backup. This will only backup a particular table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not take data backup: ' . mysql_error());
}
echo "Backedup data successfully\n";
mysql_close($conn);
?>
My very simple backup solution. Each table is saved as a separate file.
<?php
error_reporting(E_ALL);
// set the path to the backup
$bc_dir = dirname(__FILE__).'/back_db/';
// DB-connect settings
$db_user = '';
$db_name = '';
$db_pass = '';
$db_host = 'localhost';
$dsn = 'mysql:dbname='.$db_name.';host='.$db_host.'';
try {
$pdo = new PDO($dsn, $db_user, $db_pass);
} catch (Exception $e) {
var_dump($e->getMessage());
}
$query = $pdo->query('SHOW TABLES');
while ($row = $query->fetch(PDO::FETCH_NUM)) {
exec("mysqldump --user=".$db_user." --password=".$db_pass." --host="
.$db_host." ".$db_name." ".$row[0]." --skip-lock-tables --result-file="
.$bc_dir.$row[0].".sql > /dev/null 2>&1");
}
#T.Todua's answer.
It's cool. However, it failed to backup my database correctly. Hence, I've modified it.
Please use like so: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" );
Thank you.
<?php
/**========================================================+
* +
* Static class with functions for backing up database. +
* +
* PHP Version 5.6.31 +
*=========================================================+*/
class Backup_Mysql_Db
{
private function __construct() {}
/**Initializes the database backup
* #param String $host mysql hostname
* #param String $user mysql user
* #param String $pass mysql password
* #param String $name name of database
* #param String $outputDir the path to the output directory for storing the backup file
* #param Array $tables (optional) to backup specific tables only,like: array("mytable1","mytable2",...)
* #param String $backup_name (optional) backup filename (otherwise, it creates random name)
* EXAMPLE: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" );
*/
public static function init($host,$user,$pass,$name, $outputDir, $tables=false, $backup_name=false)
{
set_time_limit(3000);
$mysqli = new mysqli($host,$user,$pass,$name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//change database to $name
$mysqli->select_db($name);
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8"))
{
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
}
//list all tables in the database
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
//if user opted to backup specific tables only
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
date_default_timezone_set('Africa/Accra');//set your timezone
//$content is the text data to be written to the file for backup
$content = "-- phpMyAdmin SQL Dump\r\n-- version 4.7.4". //insert your phpMyAdmin version
"\r\n-- https://www.phpmyadmin.net/\r\n--\r\n-- Host: ".$host.
"\r\n-- Generation Time: ".date('M d, Y \a\t h:i A',strtotime(date('Y-m-d H:i:s', time()))).
"\r\n-- Server version: ".$mysqli->server_info.
"\r\n-- PHP Version: ". phpversion();
$content .= "\r\n\r\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET AUTOCOMMIT = 0;\r\nSTART TRANSACTION;\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;\r\n/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;\r\n/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8mb4 */;\r\n\r\n--\r\n-- Database: `".
$name."`\r\n--\r\nCREATE DATABASE IF NOT EXISTS `".
$name."` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;\r\nUSE `".
$name."`;";
//traverse through every table in the database
foreach($target_tables as $table)
{
if (empty($table)){ continue; }
$result = $mysqli->query('SELECT * FROM `'.$table.'`');
//get the number of columns
$fields_amount=$result->field_count;
//get the number of affected rows in the MySQL operation
$rows_num=$mysqli->affected_rows;
//Retrieve the Table Definition of the existing table
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine=$res->fetch_row();
$content .= "\r\n\r\n-- --------------------------------------------------------\r\n\r\n"."--\r\n-- Table structure for table `".$table."`\r\n--\r\n\r\n";
//if the table is not empty
if(!self::table_is_empty($table,$mysqli))
{ $content .= $TableMLine[1].";\n\n";//append the Table Definition
//replace, case insensitively
$content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
"DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
$content);//in this
$content .= "--\r\n-- Dumping data for table `".$table."`\r\n--\r\n";
$content .= "\nINSERT INTO `".$table."` (".self::get_columns_from_table($table, $mysqli)." ) VALUES\r\n".self::get_values_from_table($table,$mysqli);
}
else//otherwise if the table is empty
{
$content .= $TableMLine[1].";";
//replace, case insensitively
$content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
"DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
$content);//in this
}
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;";
date_default_timezone_set('Africa/Accra');
//format the time at this very moment and get rid of the colon ( windows doesn't allow colons in filenames)
$date = str_replace(":", "-", date('jS M, y. h:i:s A.',strtotime(date('Y-m-d H:i:s', time()))));
//if there's a backup name, use it , otherwise device one
$backup_name = $backup_name ? $backup_name : $name.'___('.$date.').sql';
//Get current buffer contents and delete current output buffer
ob_get_clean();
self::saveFile($content, $backup_name, $outputDir);
exit;
}
/** Save data to file.
* #param String $data The text data to be stored in the file
* #param String $backup_name The name of the backup file
* #param String $outputDir (optional) The directory to save the file to.
* If unspecified, will save in the current directory.
* */
private static function saveFile(&$data,$backup_name, $outputDir = '.')
{
if (!$data)
{
return false;
}
try
{
$handle = fopen($outputDir . '/'. $backup_name , 'w+');
fwrite($handle, $data);
fclose($handle);
} catch (Exception $e)
{
var_dump($e->getMessage());
return false;
}
return true;
}
/**Checks if table is empty
* #param String $table table in mysql database
* #return Boolean true if table is empty, false otherwise
*/
private static function table_is_empty($table,$mysqli)
{
$sql = "SELECT * FROM $table";
$result = mysqli_query($mysqli, $sql);
if($result)
{
if(mysqli_num_rows($result) > 0)
{
return false;
}
else
{
return true;
}
}
return false;
}
/**Retrieves the columns in the table
* #param String $table table in mysql database
* #return String a list of all the columns in the right format
*/
private static function get_columns_from_table($table, $mysqli)
{
$column_header = "";
$result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");
while($row = $result->fetch_row())
{
$column_header .= "`".$row[0]."`, ";
}
//remove leading and trailing whitespace, and remove the last comma in the string
return rtrim(trim($column_header),',');
}
/**Retrieves the values in the table row by row in the table
* #param String $table table in mysql database
* #return String a list of all the values in the table in the right format
*/
private static function get_values_from_table($table, $mysqli)
{
$values = "";
$columns = [];
//get all the columns in the table
$result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");
while($row = $result->fetch_row())
{
array_push($columns,$row[0] );
}
$result1 = mysqli_query($mysqli, "SELECT * FROM $table");
//while traversing every row in the table(row by row)
while($row = mysqli_fetch_array($result1))
{ $values .= "(";
//get the values in each column
foreach($columns as $col)
{ //if the value is an Integer
$values .= (self::column_is_of_int_type($table, $col,$mysqli)?
$row["$col"].", "://do not surround it with single quotes
"'".$row["$col"]."', "); //otherwise, surround it with single quotes
}
$values = rtrim(trim($values),','). "),\r\n";
}
return rtrim(trim($values),',').";";
}
/**Checks if the data type in the column is an integer
* #param String $table table in mysql database
* #return Boolean true if it is an integer, false otherwise.
*/
private static function column_is_of_int_type($table, $column,$mysqli)
{
$q = mysqli_query($mysqli,"DESCRIBE $table");
while($row = mysqli_fetch_array($q))
{
if ($column === "{$row['Field']}")
{
if (strpos("{$row['Type']}", 'int') !== false)
{
return true;
}
}
}
return false;
}
}

How can i synchronize two database tables with PHP?

I need to use PHP to copy data from one MySQL database to another.
I can build and array of all the values to go into the other database but first I want to make sure the database has the correct fields before inserting.
For example say I am going to be copying data from tableA to tableB.
I can set up tableB to look just like tableA but in the future I may add columns to tableA and forget to add them to tableB, then my PHP script will try to insert data into a column that doesn't exist in tableB and it will fail.
So what I want to do is compare tableA to tableB and any columns that tableA has that tableB doesn't have add them to tableB.
Can anyone tell me how to do this?
Thanks everyone, based on all your help I was able to write a PHP class that copies any columns from table A to table B if they are not already there:
class MatchTable
{
var $_table_one_name;
var $_table_two_name;
var $_table_one_db_user;
var $_table_one_db_pass;
var $_table_one_db_host;
var $_table_one_db_name;
var $_table_two_db_user;
var $_table_two_db_pass;
var $_table_two_db_host;
var $_table_two_db_name;
var $_table_one_columns = array();
var $_table_two_columns = array();
var $_table_one_types = array();
var $_table_two_types = array();
var $_table_one_link;
var $_table_two_link;
var $_isTest;
function MatchTable($isLive = true)
{
$this->_isTest = !$isLive;
}
function matchTables($table1, $table2)
{
$this->_table_one_name = $table1;
$this->_table_two_name = $table2;
if(isset($this->_table_one_db_pass))
{
$this->db_connect('ONE');
}
list($this->_table_one_columns,$this->_table_one_types) = $this->getColumns($this->_table_one_name);
if(isset($this->_table_two_db_pass))
{
$this->db_connect('TWO');
}
list($this->_table_two_columns,$this->_table_two_types) = $this->getColumns($this->_table_two_name);
$this->addAdditionalColumns($this->getAdditionalColumns());
}
function setTableOneConnection($host, $user, $pass, $name)
{
$this->_table_one_db_host = $host;
$this->_table_one_db_user = $user;
$this->_table_one_db_pass = $pass;
$this->_table_one_db_name = $name;
}
function setTableTwoConnection($host, $user, $pass, $name)
{
$this->_table_two_db_host = $host;
$this->_table_two_db_user = $user;
$this->_table_two_db_pass = $pass;
$this->_table_two_db_name = $name;
}
function db_connect($table)
{
switch(strtoupper($table))
{
case 'ONE':
$host = $this->_table_one_db_host;
$user = $this->_table_one_db_user;
$pass = $this->_table_one_db_pass;
$name = $this->_table_one_db_name;
$link = $this->_table_one_link = mysql_connect($host, $user, $pass, true);
mysql_select_db($name) or die(mysql_error());
break;
case 'TWO';
$host = $this->_table_two_db_host;
$user = $this->_table_two_db_user;
$pass = $this->_table_two_db_pass;
$name = $this->_table_two_db_name;
$link = $this->_table_two_link = mysql_connect($host, $user, $pass, true);
mysql_select_db($name) or die(mysql_error());
break;
default:
die('Improper parameter in MatchTable->db_connect() expecting "one" or "two".');
break;
}
if (!$link) {
die('Could not connect: ' . mysql_error());
}
}
function getColumns($table_name)
{
$columns = array();
$types = array();
$qry = 'SHOW COLUMNS FROM '.$table_name;
$result = mysql_query($qry) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$field = $row['Field'];
$type = $row['Type'];
/*
$column = array('Field' => $field, 'Type' => $type);
array_push($columns, $column);
*/
$types[$field] = $type;
array_push($columns, $field);
}
$arr = array($columns, $types);
return $arr;
}
function getAdditionalColumns()
{
$additional = array_diff($this->_table_one_columns,$this->_table_two_columns);
return $additional;
}
function addAdditionalColumns($additional)
{
$qry = '';
foreach($additional as $field)
{
$qry = 'ALTER TABLE '.$this->_table_two_name.' ADD '.$field.' '.$this->_table_one_types[$field].'; ';
if($this->_isTest)
{
echo $qry.'<br><br>';
}
else
{
mysql_query($qry) or die(mysql_error());
}
}
}
/**
* End of Class
*/
}
You could write a function that returns the columns from the table such as this:
function columns($table) {
$columns = array();
$sql = "desc $table";
$q = mysql_query($sql);
while ($r = mysql_fetch_array($q)) {
$columns[] = $r[0];
}
return $columns;
}
Next, you can compare the columns, from the two tables:
function tables_different($table1, $table2) {
$cols1 = columns($table1);
$cols2 = columns($table2);
return count(array_diff($cols1, $cols2)) ? true : false;
}
Now, you can integrate the tables_different() function into your data transfer script, running it each time to make sure the tables are the same.
Of course, you can make this fancier and have it tell you which columns are different between the two tables, making it more useful to synchronizing them.
I'm not a 100% sure this is what you're looking for but I used to do a little database maintenance a while back. We needed a way to make sure the devDB and the prodDB were identical in structure and I tracked down this nifty little tool. The tool creates a sql-alter-script that can be run on the database you would like to patch. It written in perl so I guess it should work cross platform but I have only tried it on linux.
The tool is called mySQLdiff, is freeware and can be downloaded at www.mysqldiff.org.
you could look into some phpclasses that do this for you
http://www.phpclasses.org/search.html?words=mysql+sync&x=0&y=0&go_search=1
SHOW COLUMNS FROM «table»
This is a very complex task and as far as I know many have tried to solved it so far (unfortunately I am not aware of any 100% guaranteed solution).
I'd say that before jumping to implement your own solution you should take a look and read about the challenges you'll be facing by reading about Schema evolution, Schema Refactoring, Schema versioning, etc.
Afterwards, you can take a look at PHP MDB2_Schema (some more documentation in this article).
If you are not tied to PHP then you may also take a look at Sundog which provides a set of advanced schema refactorings.
Once you get a reliable schema migration tool for your app, migrating data will be just a trivial task.
./alex
Probably the easiest way to do this would be
$sql = "SELECT * FROM tableA WHERE 1"
$results = mysql_fetch_assoc($sql);
$sql = "truncate table tableB";
// run truncate
foreach($result as $update){
$sql = "Insert into table b VALUES(....)"
// run insert
}
But you need to be extremely careful here. Make sure that the only process that can write to tableB is the one that does the copy from tableA other wise you will have lost data. Also make sure that nothing can write to tableA once this process has begun.
The best practice for this would be to not do this in php but rather through mysql replication.
Use TOAD for MySQL Schema compare tool, it will look at the tables, show you the differences visually and generate SQL queries to synchronize the tables structure. Also it does data compare.

Categories