我有3个表:标签,帖子,tags_post。
我正在使用Select2插件通过动态tagging
创建一个不错的选择选项用户可以从列表(TAGS表)中选择一个标签或编写自己的标签。我不知道如何编码以将新标签插入TAGS表。我只编写php将现有标签添加到关系表中。
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(将关系添加到tags_post中)此代码可以正常工作:
$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++;
}
如何在表格标签中添加新标签? (用户可以添加自己的标签)也许使用列表? ($ tags = Tags :: lists('name','id'))
我想在php中做类似的事情:
伪代码:
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
答案 0 :(得分:0)
关于插入,我可以提供以下php代码。
它可以防止SQL注入。我正在猜测id_post
的来源。
$tags = $_POST['tags'];
$id_post = $_POST['id_post'];
foreach ($tags as $value) {
$stmt = mysqli_prepare($mysqli, "INSERT INTO tags_post(id_post, id_tag) VALUES(?, ?)") or die('error '.mysqli_error($mysqli));
$stmt->bind_param('ii', $id_post, $value);
$stmt->execute() or die('error '.mysqli_error($mysqli));
}
如果您显示更多表格,我可能会帮助您。
答案 1 :(得分:0)
我自己弄清楚了(此代码对我有用):
<?php
$query_id = mysqli_query($mysqli, "SELECT id_tag FROM tags
ORDER BY id_tag DESC LIMIT 1")
or die('error '.mysqli_error($mysqli));
$count = mysqli_num_rows($query_id);
if ($count <> 0) {
$data_id = mysqli_fetch_assoc($query_id);
$id_tag_new = $data_id['id_tag']+1;
} else {
$id_tag_new = 1;
}
$id_post = $_POST['id_post'];
$tags = $_POST['tags'];
foreach ($tags as $value) {
if (is_numeric(substr($value, 0, 1))){
$query = mysqli_query($mysqli, "INSERT INTO tags_post(id_post, id_tag) VALUES('$id_post', '$value')")
or die('error '.mysqli_error($mysqli));
}
//new tag
else {
$query_new = mysqli_query($mysqli, "INSERT INTO tags(id_tag, name) VALUES('$id_tag_new', '$value')")
or die('error '.mysqli_error($mysqli));
$query_relation = mysqli_query($mysqli, "INSERT INTO tags_post(id_post, id_tag) VALUES('$id_post', '$id_tag_new')")
or die('error '.mysqli_error($mysqli));
$id_tag_new++;
}
}
?>