简体   繁体   中英

Migrate data to many-to-many using sql/php

I am trying to convert my not so well structured mysql article data to a better many-to-many structure.

basically I have on article table with fields 'article_id, title, author_1, author_2, author_3, ... , author_10' where article id is unique and the author fields hold full names.

What I need is a manay-to-many relationship where I end up with an article table of 'article_id, title' an intermediate table which holds 'article_id, author_id' and an author table which holds 'author_id, author_name'.

I know there must be a way to do this with a few lines of code. I have tried all day with puling the data out and trying to match arrays in php but getting nowhere.

Any help would be much appreciated.

It's pretty straightforward:

  • Outer loop selects all article rows from the existing table
  • For each of the author columns, insert a row into the authors table
  • After each insert, use mysql_insert_id() to get the ID of the inserted row, and insert the relationship into the article/author table.

-

$sql = "SELECT article_id, title, author_1, author_2, author_3, author_4, author_5, author_6, author_7, author_8, author_9, author_10 FROM articles";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {

  for ($i = 1; $i <= 10; $i++) {

    if (!empty($row['author_' . $i])) {

      $author = mysql_real_escape_string($row['author_' . $i]);

      //check if author exists
      $check = mysql_query("SELECT author_id FROM authors WHERE author_name = '$author'");
      if (mysql_num_rows($check) > 0) {
        $author_id = mysql_result($check,0); 
      } else {
        mysql_query("INSERT INTO authors (author_name) VALUES ('$author')");
        $author_id = mysql_insert_id();
      }

      mysql_query("INSERT INTO article_author (article_id, author_id) VALUES ({$row['article_id']}, $author_id)");
    }
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM