Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Saving slash-separated texts as categories

I want to save text separated by \ as a category. I have to save each \ to represent a subcategory. How can I go about this?

$cats = "Category \ SubCategory \ SubSubCategory";

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

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

I apply as above, but of course, I cannot give subcategory IDs to the parent_id part.

table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id -   name   -   parent_id  -  status - created_at

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

>Solution :

Ue $db->lastInsertId to get the auto-increment ID that was assigned to the last row that was inserted.

$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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading