bushdiver
bushdiver

Reputation: 771

MYSQL Adding old column as rows in new table

I have new table in database to track tags, like so:

    TAG NAME | IMAGE ID 

    funny       570
    funny       571
    dog         649

and I have old table to track tags, like so:

TAG ID | TAG NAME | IMAGES IDS

11       funny       570,571,572,573,574,575,576,577,578,579,580,581,58...
12       dog         649,650,651,652,653,654,655,656,657,658,659,660,66...
13       cat         844,845,846,847,848,849,850,851,852,853,854,855,85...

I need to add all the old image IDs / associated tags to new table

Upvotes: 1

Views: 151

Answers (2)

Techie
Techie

Reputation: 45124

You have to fetch each row and loop through and insert like below.

  1. Fetch the 1st row from the database.

  2. Use explode to explode image ids into an array.

  3. Loop through the exploded array and insert them with respective tag name.

    foreach()

    {

    //this loop with take care of the records

    //loop till the records ends

    //exploded here

    foreach()

    {

    //loop through and insert the exploded array to database

    }

    }

Upvotes: 1

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

If i am not wrong you want to add old table record to new table.

So all you need to do is query old table and explode imgid and loop through exploded string and add it in new table.

Sample Code.

<?php

    $query = mysqli_query("SELECT * FROM oldTable")or die(mysqli_error());
    while($row = mysql_fetch_assoc($query))
    {
        $ids = explode(",",$row['imageID']);

        foreach($ids as $newImgId)
        {
            $Insert_query = mysqli_query("INSERT INTO NEWTABLE ('tagname','img_id') VALUES ('".$row['tag']."','".$newImgId."')")or die(mysqli_error());
        }
    }

Upvotes: 1

Related Questions