Php 向mysql插入帖子、标签和类别的最佳方式是什么?
嗨,我有这些桌子:Php 向mysql插入帖子、标签和类别的最佳方式是什么?,php,mysql,pdo,Php,Mysql,Pdo,嗨,我有这些桌子: Table Name | column 1 | column 2 | ... Posts | ID | Title | description Tags | ID | Name Categories | ID | Title | Parent-ID Post-Tag | ID | post-id | tag-id Post-Cat | ID
Table Name | column 1 | column 2 | ...
Posts | ID | Title | description
Tags | ID | Name
Categories | ID | Title | Parent-ID
Post-Tag | ID | post-id | tag-id
Post-Cat | ID | post-id | cat-id
如何插入带有标签和类别的1篇文章?
我可以插入这样的新帖子:
$stmt = $conn->prepare("INSERT INTO Posts (title, description) VALUES ( :title, :desc)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':desc', $description);
$post_id = $conn->lastInsertId();
我每次只有一篇文章,但可能有五个标签和两个类别
如何检查标签/类别是否存在&如果存在,获取其ID;如果不存在,则获取ID并将其插入Post tag/Post cat表 下面是一些示例代码,让您了解它的工作原理
<?php
class PostRepository {
public static function tagExists($tag) {
// do your query here and return tag-id if it exists and false if it doesnt exist
}
public static function insertTag($tag) {
// do your insert query here and return the inserted id and false on failure
}
public static function insertPostTag($id_post, $id_tag) {
// do your insert query here and return the inserted id
}
public static function insertPost($title, $description, $arr_tags) {
$conn = PdoHelper::getPdoInstance(); // get your conn-obj however...
$sql = "INSERT INTO `Posts` (title, description) VALUES ( :title, :desc)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':desc', $description);
$post_id = $conn->lastInsertId();
foreach($arr_tags as $tag) {
$existing_tag = self::tagExists($tag);
if(!$existing_tag) {
$existing_tag = self::insertTag($tag);
}
self::insertPostTag($post_id, $existing_tag);
}
}
}
您标记为pdo,但您使用的是bind_param()
这是mysqli,然后是lastInsertId()
这是pdo。目前还不清楚究竟使用哪种api来连接。这些不同的API不会混合使用。修复了它。从“我的系统”复制代码时出现问题要稍微回答这个问题,您需要使用SELECT
和rowCount()。一步一步,每一步都有一个查询。没有一种查询可以让你同时完成所有的步骤。