It is not as easy as the title itself. I have a table users which has a field assignedlessons. Data stored in this field is like 69|308|50|91. As you may have already know, it keep several lessons of a user has at the same time. What I am going to do is to export data from this field along with user_id and import to another newly created table user_assigned_elearning_lessons. The structure of this table is: id, user_id, elearning_lesson_id, created_at. After the importing, the structure in the new table should be like this:
id user_id elearning_lesson_id created_at
1 1 69 2011-01-12
2 1 308 2011-04-11
3 2 50 2011-05-18
4 3 91 2011-05-21
5 3 50 2011-07-18
6 3 308 2011-07-18
How do I do that?
Despite what others have suggested, you can’t do what you want with
INSERT ... SELECTsyntax, because you’ve to split values and insert more than one row for each row of the source table.You can instead write a short PHP script to do the job, I’ve assumed the following table structure and test data:
With a PHP script you can loop over all the rows of the first table, explode the composite field into its parts and do an INSERT statement for each of those part. I’ve used
mysqliobject oriented style with prepared statements to build the insert queries.I bind the parameters to the the prepared statement with bind_param:
Where the
"ii"means that the type of those parameters is integer and integer.The output with this test data will be: