Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save tags/keywords from array to database with php?

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());
    }
?>
like image 844
Peter Westerlund Avatar asked May 21 '11 09:05

Peter Westerlund


1 Answers

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.

like image 137
zerkms Avatar answered Oct 10 '22 10:10

zerkms