Reputation: 1
I'm currently building a blog system and here is my question.
I provide several basic tags(using checkbox) for users to select.
In the same time user can also insert a new tag by clicking the button of NEW TAG!.
here is my code.
$newestTags = 0;
$title = $_POST['blog_title'] ?? '';
$content = $_POST['blog_content'] ?? '';
$tagValue = $_POST['tags'] ?? '';
$newTagFromhtml = $_POST['inserttag'] ?? '';
$totalBlog = $pdo->query("SELECT COUNT(*) from `blog`")->fetch(PDO::FETCH_NUM)[0];
$newestBlog = intval($totalBlog) + 1;
$sql = "INSERT INTO `blog`(`blog_id`,`blog_title`,`blog_content`)
VALUES(?,?,?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
$newestBlog,
$title,
$content,
]);
$tagsInsert = "INSERT INTO `blog_tagtoblog`(`tags_ID`, `blog_ID`) VALUES (?,?)";
$tags = $pdo->prepare($tagsInsert);
foreach($tagValue as $value){
$tags->execute([
$value,
$newestBlog,
]);
}
and here is my table for blog and tag
blog_tagstoblog | tags_id | blog_id |
---|---|---|
1 | 1 | 22 |
2 | 1 | 23 |
3 | 2 | 22 |
tags_id | tags_desc |
---|---|
1 | food |
2 | lunch |
also my HTML and Javascript
<p>TAGS!</p>
<?php foreach($tags as $t): ?>
<div>
<input type="checkbox" class="checkbox" name="tags[]" value="<?= $t['tags_id']?>" id="<?= $t['tags_id']?>">
<label for="<?= $t['tags_id']?>" class="form-label" id="haha"> <?= $t['tags_desc']?></label>
</div>
<? endforeach; ?>
<button class="insertNewTag">NEW TAG!</button>
</div>
<button type="submit" class="btn btn-primary">submit</button>
// javascript down below
insertNewTag.addEventListener("click", function(e) {
e.preventDefault();
input.type = "text";
input.name = "tags[]"
input.value = input.value;
spaceForNewTag.append(input);
fetch("insertArticle-api.php", {
method: 'POST',
body: fd,
}).then(res => res.json()).then(obj => {
if (obj.success || obj.tagsCheck) {
console.log(obj)
alert("OKAY!")
location.href = "articleList.php";
} else {
alert(`${obj.error}`)
}
})
})
and now my question is,
it's okay for me to insert tag that I use foreach to loop over into tagstoblog and insert tags that created by user into table of tag.
But I don't know how to fetch the tags_id of newest tag created by user and insert it into table of blog_tagstoblog.
It is possible to do that in one go?
Upvotes: 0
Views: 512
Reputation:
You can use $last_insert_id = $pdo->lastInsertId()
. Then if need, you can use it as json response and call anywhere you need.
Upvotes: 1