如何用php将标签/关键字从数组保存到数据库?

时间:2022-05-24 15:42:39

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.

很好地回答了数据库的结构。但是,在php中,哪种方法是最好的保存过程呢?处理添加和删除的过程。

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

1 个解决方案

#1


4  

I propose to select current tags and after you can do:

我建议选择当前标签,然后你可以:

$tags_to_add = array_diff($new, $old);
$tags_to_remove = array_diff($old, $new);

After that you write 2 trivial queries: one to bulk insert and one to delete.

在此之后,您将编写两个简单的查询:一个要批量插入,另一个要删除。

#1


4  

I propose to select current tags and after you can do:

我建议选择当前标签,然后你可以:

$tags_to_add = array_diff($new, $old);
$tags_to_remove = array_diff($old, $new);

After that you write 2 trivial queries: one to bulk insert and one to delete.

在此之后,您将编写两个简单的查询:一个要批量插入,另一个要删除。