Skip to content

Instantly share code, notes, and snippets.

@irfanevrens
Created November 10, 2015 16:46
Show Gist options
  • Save irfanevrens/208f0f4e6cfc71010249 to your computer and use it in GitHub Desktop.
Save irfanevrens/208f0f4e6cfc71010249 to your computer and use it in GitHub Desktop.
<?php
// comma seperated tag list
$tags = $_POST['tags'];
$contentId = $_POST['contentId'];
$tagIds = InsertTagsAndGetIds(explode(',', $tags));
foreach ($tagIds as $tagId) {
InsertContentTag($contentId, $tagId);
}
function InsertContentTag($contentId, $tagId)
{
if ( ! empty($contentId) && ! empty($tagId)) {
$query = 'INSERT INTO content_tag (content_id, tag_id) VALUES (?, ?)';
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param('ii', $contentId, $tagId);
$stmt->execute();
}
}
}
function InsertTagsAndGetIds($tags)
{
$returnIds = [];
foreach ($tags as $tag) {
if ($tagId = InsertTagAndGetId($tag))
$returnIds[] = $tagId;
}
return $returnIds;
}
function InsertTagAndGetId($tag)
{
$query = 'SELECT id FROM tags WHERE name = "' . $tag . '"';
$result = $conn->query($query);
if ($result->num_rows == 0) {
// insert tag
$query = 'INSERT INTO tags (name) VALUES (?)';
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param('s', $tag);
return $conn->insert_id;
}
return null;
} else {
return $result->fetch_assoc()['id'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment