Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i backup a SQL database using PHP?

Tags:

sql

php

backup

How do i backup a SQL database using PHP.

Is there a vendor agnostic way to do this that conforms to ANSI SQL?

If not maybe you can list how to do it for each of the database vendors?

like image 760
Gary Willoughby Avatar asked Nov 02 '08 13:11

Gary Willoughby


People also ask

Can I use PHP to pull SQL data out?

Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function mysql_query. You have several options to fetch data from MySQL. The most frequently used option is to use function mysql_fetch_array(). This function returns row as an associative array, a numeric array, or both.

What is the best way to backup MySQL database?

To back up a MySQL database, you can use either third-party tools or execute the mysqldump command from the command line. mysqldump is a command-line utility used to generate a MySQL logical database backup. It creates a single . sql file that contains a set of SQL statements.


2 Answers

Every database system comes with some program for dumping its contents.

  • PostgreSQL: pg_dump
  • MySQL: mysqldump
  • ...

You can simply call that program from PHP using system() or shell_exec().

For example, if you use PostgreSQL with enabled Ident authentication and want to dump the Database test directly as SQL text to the browser, it's as simple as:

<?php
header('Content-type: text/plain');
system('pg_dump test');
?>

When using MySQL with database user and password stored into ~/.my.cnf, it is also very simple:

<?php
header('Content-type: text/plain');
system('mysqldump test');
?>

However, don't do this:

<?php
header('Content-type: text/plain');
system('mysqldump -utestuser -ptestpassword test');
?>
because transmitting a password as command line argument is very insecure.

like image 55
vog Avatar answered Oct 21 '22 03:10

vog


I love phpmybackuppro

like image 22
kevtrout Avatar answered Oct 21 '22 05:10

kevtrout