tuff
tuff

Reputation: 13

How to let users add multiple tags using PHP and MySQL?

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

Upvotes: 1

Views: 2109

Answers (3)

Kaleb Brasee
Kaleb Brasee

Reputation: 51965

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);

Upvotes: 0

cletus
cletus

Reputation: 625485

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);
}

Upvotes: 6

Amber
Amber

Reputation: 527558

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"

Upvotes: 3

Related Questions