Home

Thursday, July 11, 2013

Database Clone using PHP

<?php
    $source_db='source';
    $target_db='target';
    
    $server='localhost';
    $user='root';
    $password='';
  
    mysql_connect($server,$user,$password);
  
   if(mysql_select_db($target_db))
   {
       $sql = "DROP DATABASE ".$target_db;
       mysql_query($sql) or die(mysql_error());
   }
  
   if(!mysql_select_db($target_db))  
   {
       $sql = "CREATE DATABASE ".$target_db;
       mysql_query($sql) or die(mysql_error());
   }
   
  
    mysql_select_db($source_db) or die(mysql_error());

    // Get names of all tables in source database
    $result=mysql_query("show tables");
    while($row=mysql_fetch_array($result)){
        $name=$row[0];
        $this_result=mysql_query("show create table $name");
        $this_row=mysql_fetch_array($this_result);
        $tables[]=array('name'=>$name,'query'=>$this_row[1]);
    }

    // Connect target database to create and populate tables
    mysql_select_db($target_db) or die(mysql_error());

    $total=count($tables);
    for($i=0;$i < $total;$i++){
        $name=$tables[$i]['name'];
        $q=$tables[$i]['query'];
         echo $i.">>>".$total;
        echo "<br>";
        mysql_query($q);
        mysql_query("insert into $name select * from $source_db.$name")  or die(mysql_error());
    }
    
?>

No comments:

Post a Comment

rathoddhirendra.blogspot.com-Google pagerank and Worth