开发者

Adding contents from multiple tables to another table

I'm working on a simple script that aims to select all the tables of a MySQL database and put their data in a different table. The tables in question are similarly structured. My objective is to accomplish this without having to w开发者_Go百科rite each table's name (so I can manage hundreds of them).

So for this example I would have alpha and beta, and want their content copied into delta. I've tried to do it with a loop that lists the names of all tables in the base. And then use a MySQL query with a variable. Problem is, it keeps returning me an error saying Table 'test_db.Resource' doesn't exist (test_db being the name of my base and Resource being... I have no idea!)

Have you any idea on how to get this done?

Here's my code:

<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("test_db") or die(mysql_error());


   $tables = mysql_list_tables("test_db");

   while (list($table) = mysql_fetch_row($tables)) {
      echo "$table <br />";
   }

// query($q);
mysql_query("INSERT INTO delta 
 SELECT null, name, age FROM $tables ") 
or die(mysql_error());

?>


<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("test_db") or die(mysql_error());


   $tables = mysql_list_tables("test_db");

   while (list($table) = mysql_fetch_row($tables)) {
      mysql_query("INSERT INTO delta 
      SELECT null, name, age FROM $table ") 
      or die(mysql_error());
   }
?>

This should work fine, but mysql_list_tables("test_db"); will also return delta, so you will have duplicate data. it will be easier to have the names of the tables in an array and loop through

$tables = array("alpha","beta");
foreach ($tables as $table){
   mysql_query("INSERT INTO delta 
          SELECT null, name, age FROM $table ") 
          or die(mysql_error());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜