如何使用php将标签/关键字从数组保存到数据库?
我看到这个问题:如何在数据库中保存标签(关键字)?
好回答数据库应该如何构建。但是在 php 中哪种方式最好进行保存过程呢?处理添加和删除的进程。
关键字以数组形式发布。
编辑: 当前的代码如下所示:
<?php
$new = explode(',', $_POST['tags']);
$query = mysql_query("SELECT * FROM pages_tags WHERE page_id = '".$page_id."'") or die(mysql_error());
while ($row = mysql_fetch_array($query))
{
$old[] = $row['tag'];
}
$tags_to_add = array_diff($new, $old);
$tags_to_remove = array_diff($old, $new);
if (is_array($tags_to_add))
{
foreach ($tags_to_add as $add_tag) { $insert_tags[] = "('".$add_tag."', '".$page_id."')"; }
$sql_insert_tags = "INSERT INTO pages_tags (tag, page_id) VALUES ".implode(',', $insert_tags);
mysql_query($sql_insert_tags) or die(mysql_error());
}
if (is_array($tags_to_remove))
{
foreach ($tags_to_remove as $remove_tag) { $delete_tags[] = "('".$remove_tag."')"; }
$sql_delete_tags = "DELETE FROM pages_tags WHERE page_id = '".$page_id."' AND tag IN (".implode(',', $delete_tags).")";
mysql_query($sql_delete_tags) or die(mysql_error());
}
?>
I saw this question: how to save tags(keywords) in database?
Good answer for how the database should be structured. But which way is best to do the saving process in php? A process that handles both adding and deleting.
The keywords are posted as an array.
Edit:
The current code look like this:
<?php
$new = explode(',', $_POST['tags']);
$query = mysql_query("SELECT * FROM pages_tags WHERE page_id = '".$page_id."'") or die(mysql_error());
while ($row = mysql_fetch_array($query))
{
$old[] = $row['tag'];
}
$tags_to_add = array_diff($new, $old);
$tags_to_remove = array_diff($old, $new);
if (is_array($tags_to_add))
{
foreach ($tags_to_add as $add_tag) { $insert_tags[] = "('".$add_tag."', '".$page_id."')"; }
$sql_insert_tags = "INSERT INTO pages_tags (tag, page_id) VALUES ".implode(',', $insert_tags);
mysql_query($sql_insert_tags) or die(mysql_error());
}
if (is_array($tags_to_remove))
{
foreach ($tags_to_remove as $remove_tag) { $delete_tags[] = "('".$remove_tag."')"; }
$sql_delete_tags = "DELETE FROM pages_tags WHERE page_id = '".$page_id."' AND tag IN (".implode(',', $delete_tags).")";
mysql_query($sql_delete_tags) or die(mysql_error());
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议选择当前标签,然后您可以执行以下操作:
之后编写 2 个简单查询:一个用于批量插入,一个用于删除。
I propose to select current tags and after you can do:
After that you write 2 trivial queries: one to bulk insert and one to delete.