开发者

PHP & MySQL display problem

I have a script that displays categories but I want the script to display only certain categories that the user picked which can range from 1 to many categories. What do I need to do to my script to fix this problem? An example would help out a lot.

Here is my PHP script.

function make_list ($parent = 0, $parent_url = '') {
    global $link;
    echo '<ol>';

    foreach ($parent as $id => $cat) {
        $url = $parent_url . $cat['url'];
        echo '<li><a href="' . $url . '" title="' . $cat['category'] . ' Category Link">' . $cat['category'] . '</a>';          

        if (isset($link[$id])) {
            make_list($link[$id], $url);开发者_JS百科 // $url adds url value to sub categories
        }               
        echo '</li>';
    }       
    echo '</ol>';
}

$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM categories ORDER BY parent_id, category ASC");
if (!$dbc) {
    print mysqli_error();
} 

$link = array();

while (list($id, $parent_id, $category, $url) = mysqli_fetch_array($dbc)) {
    $link[$parent_id][$id] =  array('category' => $category, 'url' => $url);
}

make_list($link[0]);

Here is my MySQL table.

CREATE TABLE categories ( 
id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
parent_id INT UNSIGNED NOT NULL DEFAULT 0, 
category VARCHAR(255) NOT NULL, 
url VARCHAR(255) NOT NULL,
depth INT NOT NULL DEFAULT 0, 
PRIMARY KEY (id), 
INDEX parent (parent_id),
UNIQUE KEY(parent_id, url)
);

Here is my list of categories I commented which categories I want to display.

Antiques
    Antiquities
    Architectural & Garden
        Asian Antiques
        Books & Manuscripts
            Decorative Arts
                Ethnographic
                    Furniture // I want to select this category
Home & Hearth
Linens & Textiles
Restoration & Care // I want to select this category
Rugs & Carpets // I want to select this category
Science & Medicine
Silver // I want to select this category
Reproduction Antiques


Change your query to something like this, you need to fetch category id's an insert them in IN clause.

SELECT * FROM categories WHERE categories IN(1,5,10,12) ORDER BY parent_id, category ASC


I agree with the previous post about using the IN clause. Just dynamically add them to your query though. So each time a user clicks a category (however you're allowing them to do so) you can add that category's ID to an array. Then use something like PHP's implode function to make a comma separated list implode(",", $array) So you're query string would look like

$string = "SELECT * FROM categories WHERE categories IN(" . implode(",", $selectedCats) . ") ORDER BY parent_id, category ASC"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜