1

Okay, so I already have a script to let users enter tags but I want to let users enter multiple tags that are separated by a comma for example, (html, css, php) and store each tag in the database.

Is there a tutorial that can show me how to do this or can someone give me a couple of examples that i can work from.

Thanks

3 Answers 3

6

Assuming a schema like this:

  • Post (id, author_id, post_date, post_text);
  • Tag (id, tag_name);
  • Post Tag (id, post_id, tag_id).

The Post Tag table is what's called a join table for the many-to-many relationship from Post to Tag (because a Post can have multiple Tags and a Tag can be used on multiple Posts).

The user enters a list of tags separated by commas into an input field:

$tags = array_unique(array_map(explode(',', $POST['tags']), 'trim'));

and you have an array of tags the user entered. You may want to sanitize them further, like only allowing certain characters and/or converting them to lowercase.

Then your code becomes:

$post_id = ...
foreach ($tats as $tag) {
  $tag = mysql_real_escape_string($tag);
  $sql = <<<END
INSERT INTO PostTag (post_id, tag_id)
VALUES ($post_id, (SELECT id FROM Tag WHERE tag_name = '$tag'))
END;
  mysql_query($sql);
}
Sign up to request clarification or add additional context in comments.

Comments

3

Typically what you'd do for tag<->post mappings is have 1 table for tags, 1 table for posts, and then a third table which stores pairings between them:

tagid tagname
-------------
1     foo
2     bar

postid posttitle
-------------
1      test
2      beep

tagid postid
-------------
1     2
2     1
2     2

Would have two posts, where the first is tagged "bar" and the second is tagged "foo, bar"

3 Comments

Is the question rather not about normalization but how in fact to normalize with CSV input?
I was looking for more how to let users add multiple tags and separating them apart and storing them. I already have the database designed.
Ah. In that case, explode() is probably the easiest way to parse the string.
0

You could split a string of multiple tags using the PHP preg_split command, and then save each tag to the database as you do now.

The following code would split the string "html, css, php" into an array ["html", "css", "php"]:

$tag_string = "html, css, php";
$tags = preg_split("/[\s,]+/", $tag_string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.