Reputation: 938
I have a function which gets me all tables with their columns from an old database to a new database. Everything is working fine so far. Now I need to extend that function, so that in all tables inside my new database a surrogate key (primary key ID with auto increment) will be added.
Old DB:
+-----------------------------------+------------+--------+
| Col1 | Col2 | NumCol |
+-----------------------------------+------------+--------+
| Value 1 | Value 2 | 123 |
| This is a row with only one cell | | |
| This row is testing html entities | Te<br />st | 45 |
+-----------------------------------+------------+--------+
New DB:
+----+-----------------------------------+------------+--------+
| ID | Col1 | Col2 | NumCol |
+----+-----------------------------------+------------+--------+
| 1 | Value 1 | Value 2 | 123 |
| 2 | This is a row with only one cell | | |
| 3 | This row is testing html entities | Te<br />st | 45 |
+----+-----------------------------------+------------+--------+
So as you can see, everything remains the same except the new column ID in every table.
Here is my function to copy everything from my old DB to my new DB:
public function loadOldDBtoNewDB($oldDB,$newDB){
$sqlshowTables = "SHOW TABLES ";
$statement = $this->db->prepare($sqlshowTables);
$statement->execute();
$tables = $statement->fetchAll(PDO::FETCH_NUM);
foreach($tables as $table){
$sql[] = "INSERT INTO ".$newDB.".`".$table[0]."` SELECT * FROM ".$oldDB.".`".$table[0]."`; ";
}
$sqlState = implode(' ', $sql);
$executeStatement = $this->db->exec($sqlState);
}
Note: Old DB and new DB already exist when I run this function.
So how do I need to change my inser statement so that an ID (auto increment) column will be added during every insert?
Upvotes: 1
Views: 89
Reputation: 169
u can also create new table with following command
create table new_table as (select * from old_table);
alter table new_table add column id primary key auto_increment;
Upvotes: 1
Reputation: 26460
Your new table should already have an AUTO_INCREMENT
on the id
column. Then supply a NULL
value to it when doing the select!
If your new table doesn't have auto-increment set on the ID
column, add it by
ALTER TABLE `mytablename`
CHANGE `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT
Add a NULL
before the *
in your SELECT
- this will force the ID
(which appears first in your column-list) to use the AUTO_INCREMENT
, since it cannot be NULL
.
$sql[] = "INSERT INTO ".$newDB.".`".$table[0]."` SELECT NULL, * FROM ".$oldDB.".`".$table[0]."`; ";
Upvotes: 1