Stuck on the logic of creating tags for posts (like SO tags)? (PHP)

Posted by ggfan on Stack Overflow See other posts from Stack Overflow or by ggfan
Published on 2010-04-07T02:09:17Z Indexed on 2010/04/07 2:13 UTC
Read the original article Hit count: 500

Filed under:
|
|

I am stuck on how to create tags for each post on my site. I am not sure how to add the tags into database. Currently... I have 3 tables:

+---------------------+    +--------------------+    +---------------------+
| Tags                |    | Posting            |    | PostingTags         |
+---------------------+    +--------------------+    +---------------------+
| + TagID             |    | + posting_id       |    | + posting_id        |
+---------------------+    +--------------------+    +---------------------+
| + TagName           |    | + title            |    | + tagid             |
+---------------------+    +--------------------+    +---------------------+

The Tags table is just the name of the tags(ex: 1 PHP, 2 MySQL,3 HTML) The posting (ex: 1 What is PHP?, 2 What is CSS?, 3 What is HTML?) The postingtags shows the relation between posting and tags.

When users type a posting, I insert the data into the "posting" table. It automatically inserts the posting_id for each post(posting_id is a primary key).

    $title = mysqli_real_escape_string($dbc, trim($_POST['title']));
    $query4 = "INSERT INTO posting (title) VALUES ('$title')";
    mysqli_query($dbc, $query4);

HOWEVER, how do I insert the tags for each post? When users are filling out the form, there is a checkbox area for all the tags available and they check off whatever tags they want. (I am not doing where users type in the tags they want just yet)

This shows each tag with a checkbox. When users check off each tag, it gets stored in an array called "postingtag[]".

<label class="styled">Select Tags:</label>
    <?php

 $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
 $query5 = "SELECT * FROM tags  ORDER BY tagname";
 $data5 = mysqli_query($dbc, $query5);
 while ($row5 = mysqli_fetch_array($data5)) {
    echo '<li><input type="checkbox" name="postingtag[]"
        value="'.$row5['tagname'].'" ">'.$row5['tagname'].'</li>';
    }

 ?>

My question is how do I insert the tags in the array ("postingtag") into my "postingtags" table? Should I...

    $postingtag = $_POST["postingtag"];
foreach($postingtag as $value){
$query5 = "INSERT INTO postingtags (posting_id, tagID) 
               VALUES (____, $value)";
mysqli_query($dbc, $query5);
}       

1.In this query, how do I get the posting_id value of the post?

I am stuck on the logic here, so if someone can help me explain the next step, I would appreciate it!

Is there an easier way to insert tags?

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql