Basic database export script

from the Artful MySQL Tips List


For occasions where the server offers access to neither mysqldump nor phpMyAdmin, here is a basic PHP script for exporting a database and its data to an HTML page, from which you can copy & paste the result to anywhere you like. You may have to touch up the script (we've used it only occasionally). To use it, fill in the four variable values at the top of the page, and run it as you would any PHP browser script.

<?php
$host
="...";
$user "...";
$pswd "...";
$db "...";

$conn mysql_connect($host,$user,$pswd) or die( mysql_error());
mysql_select_db$db ) or die( mysql_error() );
$res mysql_query"show tables" ) or die( mysql_error() );
echo 
"set @fkeychecks=@@foreign_key_checks;<br/>set foreign_key_checks=0<br/>;";
while( 
$row mysql_fetch_row$res )) {
  
$tbl $row[0];
  
$resddl mysql_query"SHOW CREATE TABLE $tbl) or die( mysql_error() );
  
$ddl mysql_fetch_row$resddl ) or die( mysql_error() );
  echo 
"<br/>-- Structure & data of $db.$tbl<br/>" nl2br($ddl[1]) . ";<br/>";
  
$resdata mysql_query("select * from $tbl") or die( mysql_error() );
  
$rows mysql_num_rows$resdata ); 
  if( 
$rows ) continue;
  
$cols mysql_num_fields$resdata );
  while( 
$data mysql_fetch_row$resdata )) {
    
$ins "INSERT INTO $tbl VALUES(";
    for( 
$i=0$i $cols$i++ ) {
      
$type mysql_field_type$resdata$i );
      
$val $data[$i];
      if( 
stripos"datetime|timestamp|string|blob|char"$type ) != false $val "'" $val "'";
      
$ins .= $val;
      if( 
$i+$cols $ins .= ",";
    }
    
$ins .= ");<br/>";
  }
  if( !empty( 
$ins )) echo $ins;
}
echo 
"set foreign_key_checks=@fkeychecks<br/>;";
mysql_close$conn );
?>


Return to the Artful MySQL Tips page