简体   繁体   中英

Search column with comma separated string

Currently I am using the query below together with a recursive function to print a menu.

"SELECT * FROM categories WHERE FIND_IN_SET('".$parent."', parentId)"

DB structure: 在此处输入图片说明

The result by printing this out is:

Smycken
--| Halsband
--|--| Guld
--|--|--| test
--|--|--|--| test2
--|--| Silver
--| Armband
Honung

Row 10, parentId . I got two values separated with a comma (I've read that this is not the ultimate way to store values, but I'll do it anyway), now I want row 10 to be printed out like a subcategory, just like my other rows are being printed out. The solution I found was to use FIND_IN_SET or use LIKE, I get neither of them to work as I wish...

Suggestions or a solution for my problem?

This is my function:

function getSubCat($level = 0, $parent = 0)
{                                               


$hasChildren = false;
$outputHtml = '%s';
$childrenHtml = '';

$dbh = getdbh();

$getSubCategory = $dbh->prepare("SELECT * FROM categories WHERE FIND_IN_SET('".$parent."', parentId)");
$getSubCategory->execute();
$categories = $getSubCategory->fetchAll();
foreach($categories as $category)
{

    if ($category['parentId'] == $parent) {
        $hasChildren = true;
        $childrenHtml .= '<option value="'.$category['id'].'">';

        for($k = 0 ; $k < $level; $k++) {
            $childrenHtml .= '--|';
        }

        $childrenHtml .= ' '.$category['name'];
        $level++;
        $childrenHtml .= '</option>';
        $childrenHtml .= getSubCat($level, $category['id']);         
        $level--;                                                       
    }
}

if (!$hasChildren) {
    $outputHtml = '';
}

    return sprintf($outputHtml, $childrenHtml);
}

Change this line:

if ($category['parentId'] == $parent) {

to:

if (in_array($parent, explode(',', $category['parentId']))) {

The == test won't look for an element in a comma-separated string.

Actually, you don't need this if at all. The WHERE clause in the SQL already guarantees that $parent is in $category['parentId'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM