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());
}
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With