Gooey
Gooey

Reputation: 4778

Insert query into a many to many relationship database

Previously I asked how to run a fetch query on a many to many relation ship database, as I am progressing with the learning path of SQL + PHP and I ran into the following rather complex situation:

I've got a database with the following tables:

Songs       Link        Tags
=======     =====       =========
Sid          Sid        Tid
Songname     Tid        Tagname

How do you create (in PHP with a HTML form) a set of queries that check for the following:

A new song is enterred with some tags. You add the Song to the Songs table (fairly easy) and the Sid auto increments.
The tags need also to be stored, but not double. How do you create a way to check if the tags entered are not in the tags table already? if not add them and if they are already in there skip them.
On top of that the link table must also be (automatically and correctly) filled with the info. The new Sid must be linked with the new added / old tags out of the Tags table.

I don't even know if this complex series of queries is possible, but doing this by hand grows rapidly out of control, so I thought an automated way is the way to go.

So far I've got the following part of code to test with (the code obviously doesn't do much at this point, as it's only to illustrate what I'm up to):

<?php

if(isset($_POST['song']) && isset($_POST['tags'])){
$song = $_POST['song'];
$temptag = $_POST['tags'];

$tags = explode(",", $temptag);

$connection = mysql_connect("servername","db","password");
if (!$connection)
  {
  die('Could not connect: ' . mysql_error());
  }

  $query = "INSERT INTO Songs VALUES ('','$song')"; #add song
  mysql_query($query);

  # now for the tags...
  mysql_close($connection);
  echo "Song added";
}
else{
?>

<form action="add.php" method="post">
<input type="text" name="song" /> <br/>
<input type="text" name="tags" value="tag1,tag2,tag3" /> <br/>
<input type="submit" value="add song" />
</form>
<?php
}
?>

Thanks in advance.

Upvotes: 1

Views: 4607

Answers (1)

d4rkpr1nc3
d4rkpr1nc3

Reputation: 1827

Add this after you insert the song

$song_id = mysql_insert_id();
$tags = explode("," , $_POST['tags']);
foreach($tags as $tag) {
    // check if the tag already exists
    $res = mysql_query("SELECT * FROM `Tags` WHERE `Tagname` = '".$tag."' LIMIT 1");
    if(mysql_num_rows($res) == 0) {
        // if it doesn't exist, we add it
        mysql_query("INSERT INTO `Tags` VALUES ('' '".$tag."')");
        // get the last id inserted
        $tag_id = mysql_insert_id();
    } else {
         // if found, get it's id
         $tag = mysql_fetch_assoc($res);
         $tag_id = $tag[0]['id'];
    }
    // linkage
    mysql_query("INSERT INTO `Link` VALUES ('".$song_id."', '".$tag_id."')");
}

Upvotes: 2

Related Questions