0
votes

I don't know how to explain it, maybe this is understandable. I have 2 table:

  1. Table tags: (tagID: '1', '2', '3') (tagName: 'a', 'b', 'b')
  2. Table tag_posts: (postID: '1', '1', '2') (tagID: '1', '2', '3')

Output: Post 1 tagged (a[id=1], b[id=2]) and post 2 tagged (b[id=3])

But, i want result like this:

  1. Table tags: (tagID: '1', '2') (TagName: 'a', 'b')

  2. Table tag_posts: (postID: '1', '1', '2') (tagID: '1', '2', '2')

Output: Post 1 tagged (a[id=1], b[id=2]) and post 2 tagged (b[id=2])

I want on table "tags" tag name, b is 2; not b = 2 and b = 3 (not double tag name)

Php

$last_post_id = mysqli_insert_id($connect);

foreach($tags as $tag){
  $sql = mysqli_query($connect, "SELECT * FROM tb_tags WHERE tagName = '$tag'") or die(mysqli_error());
  $row = mysqli_fetch_array($sql);
  if($row == NULL){
    mysqli_query($connect, "INSERT INTO tb_tags (tagName) VALUES ('$tag')") or die(mysqli_error());
    $last_tag_id = mysqli_insert_id($connect);
    mysqli_query($connect, "INSERT INTO tb_tag_posts (postID, tagID) VALUES ('$last_post_id', '$last_tag_id')") or die(mysqli_error());
  }else{
  // if tags name exists do nothing and take the existing id tag
    mysqli_query($connect, "INSERT INTO tb_tag_posts (postID, tagID) VALUES ('$last_post_id', '".$row['tagID']."')") or die(mysqli_error());
  }
}
1
For reference, people who frequent the MySQL tag here expect to see tabular sample data, rather than what you have posted above. Please try to make your question more clear if possible. - Tim Biegeleisen
Not really clear what you're asking here but maybe you need a constraint on your table so the tag must be unique. - user3783243
Before adding a new tag, you could simply search the tags table for a tag that has the same name. If you don't find any, insert the new tag and use that id. If it does exist, use the existing id instead. - Magnus Eriksson
i update my question - Lingga Novandra
@Magnus Eriksson do you have a link for instructions? or keywords on google? - Lingga Novandra

1 Answers

0
votes

mysqli_fetch_array: Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter. from http://php.net/manual/en/mysqli-result.fetch-array.php

I think that you need to have your code like this: if($row == null){