user3188987
user3188987

Reputation: 1

How to create a backup of database using php script. I am facing a error

I m trying this code but it shows a error

"Could not take data backup:

Can't create/write to file '\transfer\employees.sql' (Errcode: 2)"

when I click on my button to create a backup file.

<?php
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbdatabase = "ghis_verf";
$conn = mysql_connect($dbhost,$dbusername,$dbpassword);
if(! $conn )
{
      die('Could not connect: ' . mysql_error());
}
$table_name = "employees";
$backup_file  = "/transfer/employees.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
mysql_select_db($dbdatabase,$conn) or die("Cannot select database");
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
    die('Could not take data backup: ' . mysql_error());
}
echo "Backedup  data successfully\n";
?>

Upvotes: 0

Views: 296

Answers (3)

sagunms
sagunms

Reputation: 8515

It may be due insufficient write privilege. If you're using Linux, you may want to create the folder first as a placeholder with sufficient permissions for Apache to write to:

$ cd /path/to/app
$ mkdir transfer
$ chmod 777 transfer

See if the following PHP script works for you:

<?php
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbdatabase = "ghis_verf";
$table_name = "employees";
$backup_file = "transfer/employees.sql";
$cmd = "mysqldump -h {$dbhost} -u {$dbusername} -p '{$dbpassword}' {$dbdatabase} {$table_name} > {$backup_file}";
system($cmd);
?>

Also /transfer is the absolute root path in your file system. Maybe it's something like /var/www/transfer? Or change it to absolute path such as transfer/.

Hope it helps.

Upvotes: 1

Bhaktaraz
Bhaktaraz

Reputation: 491

Please check the link below to export database via PHP code. Hope this will work for you. http://phptipmaster.blogspot.com/2013/01/mysql-database-export-via-php-code.html

Upvotes: 0

ScayTrase
ScayTrase

Reputation: 1830

I think you do not have folder /transfer at the root of your web server or does not have permissions to write to it.

Make sure you can perform su -c "touch /transfer/employees.sql" www-data (replace www-data with proper user for you system). If no - check permissions or folder existence.

Upvotes: 1

Related Questions