tags:

views:

23

answers:

1

Hi, i'm using php and mysql for a webpage, and i want to reuse information which i have in three database tables, similar to a 'save as' operation.

The tables are related as a 1-many and then 1-many, a tree structure.

I have so far implemented it by flatten out the tree structure with php (similar to one giant table) and storing it in an array. Then looped over every row, and even every part of the row, and for each one inserted into the corresponding table with a query. It sort of works, but with a lot of code to see if every post even has the information from the third table (it could be empty).

Now, my question is, could this be implemented in a more efficient way? There could be a lot of queries to the database this way.

The problem here seems to be how to relate the new posts. I have looked at 'SELECT INTO', but as i need to relate the new keys, i don't see how it could work. Also, mysql_insert_id only give me the latest id, not all of them.

A: 

The usually fastest and most elegant method to duplicate a row that I know of is:

Duplicating the row:

INSERT INTO tablename SELECT * FROM tablename WHERE id = 1;

querying the ID of the new record:

SELECT LAST_INSERT_ID() AS lastID;  

Storing that ID in a PHP variable (not shown here) and then updating the key in dependent tables:

UPDATE related_table_name SET key = '$lastID'

(id needs to be an auto-increment column for this to work, and LAST_INSERT_ID() should be used immediately after the insert.)

Reference:

Pekka
Thank you for your answer. This is a lot clearer than what i'm currently have. I didn't consider an UPDATE statement because it didn't sound appropriate for the task of inserting new rows. The only part of the question left unanswered is: if it is possible to avoid doing one query for every row.
Sten-Åke Strid
@Sten It might be using some SQL magic `INSERT into tablename1, tablename2...` or something - I don't know. I think the performance gain will be minuscule. If you don't have real performance problems with this, I'd say go with separate queries.
Pekka
Well, i don't, so i will go with separate queries. I'm just curious if it could be done, i'm still learning mysql so i don't really know what can or can't be done.
Sten-Åke Strid