将斜杠分隔的文本保存为类别

Saving slash-separated texts as categories

我想将以 \ 分隔的文本保存为一个类别。我必须保存每个 \ 来代表一个子类别。我该怎么做?

$cats = "Category \ SubCategory \ SubSubCategory";

$categories = explode ("\",$cats);

foreach($categories as $category){
    
    $db->query("INSERT INTO `cat` SET 
        name = '" . $category . "', 
        parent_id = '0'
    "); 
}

我按照上面的方式申请,当然,我不能给parent_id部分的子类别ID。

table

id -   name   -   parent_id  -  status - created_at

1  - Category       - 0
2  - SubCategory    - 1
3  - SubSubCategory - 2

使用 $db->lastInsertId 获取分配给插入的最后一行的 auto-increment ID。

$stmt = $db->prepare("INSERT INTO cat (name, parent_id) VALUES (:name, :parent)");
$stmt->bindParam(':name', $category);
$stmt->bindParam(':parent', $parent);
$parent = 0;
foreach ($categories as $category) {
    $stmt->execute();
    $parent = $db->lastInsertId;
}