簡體   English   中英

PHP和MySQL顯示問題

[英]PHP & MySQL display problem

我有一個顯示類別的腳本,但我希望該腳本僅顯示用戶選擇的某些類別,范圍從1到許多類別。 要解決此問題,我需要對腳本執行什么操作? 一個例子會很有幫助。

這是我的PHP腳本。

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); // $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]);

這是我的MySQL表。

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)
);

這是我的類別列表,我已評論了要顯示的類別。

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

將查詢更改為類似的內容,您需要獲取類別ID,並將其插入IN子句中。

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

我同意上一篇有關使用IN子句的文章。 只是動態地將它們添加到您的查詢中。 因此,每次用戶單擊類別時(無論您允許他們這樣做),都可以將該類別的ID添加到數組中。 然后使用類似PHP的implode函數,以逗號分隔的列表implode(",", $array)這樣,您查詢的字符串看起來像

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM