I have 3 tables: tags, posts, tags_post.
I'm using the Select2 plugin to create a nice select option with dynamic tagging
The user can pick a tag from the list (TAGS table) or write their own tag. I don't know how to code to insert new tags to the TAGS table. I only code the php to add the existing tags to the relation table.
FORM:
<select class="js-basic-multiple form-control" name="tags[]" multiple="multiple">
<?php
$query = mysqli_query($mysqli, "SELECT id_tag, name FROM tags ORDER BY name ASC;")
or die('error '.mysqli_error($mysqli));
while ($data = mysqli_fetch_assoc($query)) {
echo"<option value=\"$data[id_tag]\">$data[name] </option>";
}
?>
</select>
PHP (adds the relation in tags_post) This code works fine:
$id_post = $_POST['id_post'];
$tags = $_POST['tags'];
$i = 0;
$nTags = count($_POST['tags']);
while ($i <= $nTags){
foreach ($tags as $value) {
$query = mysqli_query($mysqli, "INSERT INTO tags_post(id_post, id_tag) VALUES('$id_post', '$value')")
or die('error '.mysqli_error($mysqli));
}
$i++;
}
How can I add the new tags in the table tags? (The user can add their own tags) Maybe using lists? ($tags= Tags::lists('name','id'))
I would like to do something like that in php:
Pseudocode:
1. Tag exists in table “tags”?
1.1 No > INSERT INTO tags
2. Insert all tags in the relation table.
2.1 INSERT INTO tags_post
$id_post
somewhere in the form, for example as a hidden input field. Also read SQL Injection – Adder