Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I categorize article submitted to sql database?

Tags:

sql

php

mysql

pdo

How do I categorize article submitted to sql database so that when user wanted to post an article to certain category, they're given an dropdown menu to select what article to publish in that category. The about us, products, and support are example of the categories

<form method="post" action="postArticle.php">
<p>
    <select name="selectedOption">
        <optgroup label="About us">
            <option value="about">About us</option>
        </optgroup>

        <optgroup label="Products">
            <option value="foo">Foo</option>
            <option value="oof">Oof</option>
        </optgroup>

        <optgroup label="Support">
            <option value="support">Support</option>
        </optgroup>
    </select>
</p>
like image 665
siaooo Avatar asked Nov 14 '22 10:11

siaooo


1 Answers

On first look it would appear that you just need a simple table to implement the structure which would allow you to create a nested array of the category structure. Any category with a parent_id == 0 is an optgroup and then you would list each sub-categories as an option within each parent optgroup.

category_id    | parent_id    | category_name
1              | 0            | About us
2              | 1            | About us
3              | 0            | Products
4              | 3            | foo
5              | 3            | oof
6              | 0            | Support
7              | 6            | Support

This would be output as:

<form method="post" action="postArticle.php">
<p>
    <select name="selectedOption">
        <optgroup label="About us">
            <option value="2">About us</option>
        </optgroup>

        <optgroup label="Products">
            <option value="4">Foo</option>
            <option value="5">Oof</option>
        </optgroup>

        <optgroup label="Support">
            <option value="6">Support</option>
        </optgroup>
    </select>
</p>

You can obviously then store the value from the select in the article table to link to the category table. Note that you can't select the parent categories in the above, only the subcategories (which you may wish to be the case). Obviously if you were to have lots of groups with only one subcategory (which duplicates the parent category name) then this isn't very efficient and you might want to look at how you're structuring your categories, or you may instead want to drop the optgroup altogether and just visually indent the labels for the subcategories under each category. That way every category (including parents) become an option and are selectable though, which you may not want.

like image 141
Paul Campbell Avatar answered Nov 16 '22 03:11

Paul Campbell