Mysql (or other) dump in PHP

I a lot of sourcode I see the calling of mysqldump to dump tables. Doing so needs all kind of OS dependent path settings and so on, so I thought I share a simple function for dumping a table from MySQL in PHP:

function _mysqlDump($table, $toFile) {
$f = fopen($toFile, "w");
$qry = "select * from $table";
$q = mysql_query($qry);
if (!$q) {
echo "Could not dump $tablen";
while($r = mysql_fetch_assoc($q)) {
$i1 = ""; $i2 = "";
foreach($r as $k=>$v) {
if ($i1) {$i1.=","; $i2.=",";}
$v = mysql_real_escape_string($v);
fputs($f, "insert into $table ($i1) values ($i2);n");

The advantage of this is that it creates total inserts which is handy when you want to recreate the database with the content intact.

Inserting the content back into the database is trivial ofcourse:

$f = fopen($toFile, "r");
while($s=fgets($f, 128000)) {
if (trim($s)) mysql_query($s);

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>