Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

php to merge mysql tables

Status
Not open for further replies.

compudude86

IS-IT--Management
Jun 1, 2006
46
0
0
hello,
i have a web interface built to show the output of several tables that distributors can edit, now i need to find a script that can take all those tables, and merge/update them into a single table on a second database. any ideas?
 
sorry, i must add that this is a mysql database, and there are give or take 10 tables on database "dist" and one public book on database "book
 
since you are posting in the php forum, I assume you want a php solution.

do all the tables have identical columns?
 
yes, they are all identical columns in each table.
 
use with care. i have not tested this.

do this for the first database and then for the second separately. i don't think you can merge across databases using more or less pure sql like this but you can ask in the mysql forum.

if no joy then open two db connections to each of the two merged tables. use a select * query on one to get the full recordset and then iterate that recordset doing an insert into the other.

Code:
$tables = array("table1","table2","table3"); //etc
$pk = "";//name of autoincrementing primary key [assumption]
mysql_query("Create table newtable like table1");
foreach ($tables as $table){
 mysql_query("Insert into newtable select * from $table on duplicate key update $pk = last_insert_id()+1");
}
 
see, i dont want to create a new table, i want it to take all the tables on dist, and apply an update to database/table "book:products". basically i need a php app that i can click an update button that will run all this "behind the scenes
 
i'd still do what i said.

use mysql to aggregate all the tables that are on dist,
use php to grab the recordset in the new table and bung it into book:products.

then just add a drop table to kill the newly aggregated version.

the php bit might look something like this (minus the drop table):

Code:
<?
mysql_connect(	$databaseserver, 
				$dbUsername, 
				$dbPassword	);

$client = mysql_select_db("dist");
$host = mysql_select_db("book");

$clientquery = mysql_query($client, $client);
$inserts = array();
while ($row = mysql_fetch_assoc($clientquery)){
	$insert = "";
	foreach ($row as $col=>$val){
		$insert .= " $col='$val', ";
	}
	$insert = "Insert 
				into products 
			   set
			". rtrim($insert, ",") . 
			" on duplicate update $pk = last_insert_id()+1 ";
	mysql_query($insert, $host);
}
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top