Link to home
Start Free TrialLog in
Avatar of secuteamers
secuteamersFlag for Belgium

asked on

PHP script for mysql database export

Does anyone have a function or script to export a database structure with content (create table, inserts, ....) without using mysqldump. A less complexe version of phpmyadmin.

The result should look like this:

--
-- Table structure for table `nics`
--

DROP TABLE IF EXISTS nics;
CREATE TABLE nics (
  id int(11) NOT NULL auto_increment,
  fid int(11) NOT NULL default '0',
  nicname varchar(100) NOT NULL default '',
  ip varchar(100) NOT NULL default '',
  netmask varchar(100) NOT NULL default '',
  dgateway varchar(100) NOT NULL default '',
  comment varchar(100) NOT NULL default '',
  trusted tinyint(4) NOT NULL default '0',
  bridge tinyint(4) NOT NULL default '0',
  mac varchar(100) NOT NULL default '',
  user varchar(100) NOT NULL default '',
  pass varchar(100) NOT NULL default '',
  dhcp tinyint(4) NOT NULL default '0',
  downspeed varchar(100) NOT NULL default '',
  bridgeid int(11) NOT NULL default '-1',
  PRIMARY KEY  (id)
) TYPE=MyISAM;

--
-- Dumping data for table `nics`
--


/*!40000 ALTER TABLE nics DISABLE KEYS */;
LOCK TABLES nics WRITE;
INSERT INTO nics VALUES (146,1,'eth0','dssqd','qdssqd','','',0,0,'','','',0,'',-1),(147,1,'eth1','','','','',0,0,'','user','pass',0,'',-1),(139,1,'br0','*****','','','',1,1,'','','',0,'',-1),(143,1,'eth11','','','','',0,0,'','','',0,'',139);
UNLOCK TABLES;
/*!40000 ALTER TABLE nics ENABLE KEYS */;
Avatar of ldbkutty
ldbkutty
Flag of India image

>> A less complexe version of phpmyadmin.
Do you mean you dont want to use PhpMyAdmin or what ?
Avatar of secuteamers

ASKER

indeed, i have a web application that has to backup my database whenever requested by a form.  I know it can be done with phpmyadmin and i have it done with passthru("mysqldump ....") but since i dont want to use shell commands and i have an urgent deadline, i just need a simple function to do it. I would truly appreciate it. Maybe even donate some extra points.
>> ..since i dont want to use shell commands ..
You dont need to use shell commands in phpmyadmin. There's an "export" feature.  You select the tables you wish to export, click the options "structure" and "data" and the option to "save as file".  It will generate a file with a .sql extension.

If this is not what you want, please tell me your OS, PHP and MySQL versions.
Or get MySQL Front and export the tables.
http://www.mysqlfront.de/download.html
My os is debian linux, mysql 4, php4
I know there is an export feature in phpmyadmin, i just want to use this feature for only one database. The function in phpmyadmin is spread over many files. I could analyze it, but in that time i could write it myself. Since i dont have a lot of time till my deadline, i dont want to focus on analysis. Hope someone can help me.
Avatar of frugle
frugle

If the function you needed was simple, phpmyadmin would use it.

Could you put a form into your web app:

<form method="post" action="path/to/phpmyadmin/tbl_dump.php" name="db_dump">
<input type="hidden" name="lang" value="en-iso-8859-1" />
<input type="hidden" name="server" value="1" />
<input type="hidden" name="db" value="databasename" />
<input type="hidden" name="table_select[]" value="tablename">
..
..
..
<input type="hidden" name="asfile" value="sendit" id="checkbox_dump_asfile">
<input type="hidden" name="" value="">
<input type="submit" value="export database">
</form>

and for security, remove the phpmyadmin files that are not used?

Mike
ASKER CERTIFIED SOLUTION
Avatar of _GeG_
_GeG_

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thx for the function. I used the script for creating the database structure, but for the content part, ive written it myself, here it is:

include("../scripts/conn.php");

function get_structure($dbname)
{
    $tables = mysql_list_tables($dbname);
    while ($td = mysql_fetch_array($tables))
    {
        $table =  $td[0];
        $r = mysql_query("SHOW CREATE TABLE `$table`\r");
        if ($r)
        {
            $d = mysql_fetch_array($r);
                  //$SQL[] = "\r\r--\r-- DROP THE TABLE\r--";
                  //$SQL[] = "DROP TABLE IF EXISTS `$table`";
                  //$SQL[] = "--\r-- CREATE THE TABLE\r--";
                  $SQL[] = "DROP TABLE IF EXISTS `$table`;";
            $SQL[] = str_replace("\n", "", "$d[1];");

                  echo "<br><br>--<br>-- DROP THE TABLE<br>--<br>";
                  echo "DROP TABLE IF EXISTS `$table`<br><br>";
                  echo "--<br>-- CREATE THE TABLE<br>--<br>";
            echo $d[1];
        }
    }
    return $SQL;
}

function get_content($dbname)
{
    $tables = mysql_list_tables($dbname);
    while ($td = mysql_fetch_array($tables))
    {
        $table =  $td[0];
        $r = mysql_query("SELECT * FROM `$table`\r");
            $fieldcount = mysql_num_fields($r);
            echo "<br><br>--<br>-- INSERT IN `$table`<br>--<br>";
        while($row = mysql_fetch_array($r))
        {

                  $fields = "";//RESET OP LEEG
                  $values = "";//RESET OP LEEG
                  for($i=0;$i<$fieldcount;$i++){
                        $fieldtype = mysql_field_type($r,$i);
                        if($i != $fieldcount-1){
                              $fields .= $table.".".mysql_field_name($r,$i).",";
                              if($fieldtype == "string" || $fieldtype == "blob"){
                                    $values .= "'".str_replace("'","\'",$row[mysql_field_name($r,$i)])."',";
                              }else{
                                    $values .= $row[mysql_field_name($r,$i)].",";
                              }
                        }else{
                              $fields .= $table.".".mysql_field_name($r,$i);
                              if($fieldtype == "string" || $fieldtype == "blob"){
                                    $values .= "'".str_replace("'","\'",$row[mysql_field_name($r,$i)])."'";
                              }else{
                                    $values .= $row[mysql_field_name($r,$i)];
                              }
                        }
                  }

                  $SQL[] = "INSERT INTO `$table`(".$fields.")VALUES(".$values.");";
                  echo "INSERT INTO `$table`(".$fields.")VALUES(".$values.")<br>";
        }
    }
    return $SQL;
}

function save_structure($dbname, $filename)
{
    $structure = get_structure($dbname);
      $content = get_content($dbname);
    $fh = fopen($filename, "w");
    fwrite($fh, implode("\r", $structure));
    fwrite($fh, implode("\r", $content));
    fclose($fh);
    $result = ($sql != "") && $fh;
}

function create_structure ($dbname, $filename)
{
    $lines = explode("\n", file_get_contents($filename));
    $result = true;
    foreach ($lines as $line)
        $result = $result && mysql_query($line);
    return $result;
}
save_structure("axsweb","test.sql");
echo "database structure backup done";
one small thing to notice, mysql does insert much faster in one command:
insert into table (vars...) VALUES (...), (...), (....), (...)
is faster than
insert into table (vars...) VALUES (...)
insert into table (vars...) VALUES (...)
...
see http://dev.mysql.com/doc/mysql/en/Insert_speed.html

oh, and I just noticed my code misses the ') VALUES' part ;)