数据库中的类别树。使可点击的cat_parent_id> 0

问题描述 投票:0回答:1

我有这个脚本从数据库中获取类别树并在html SELECT中显示它

function CategoryTree(&$output=null, $cat_parent_id=0, $indent=null){

$con = new PDO("mysql:host=localhost;dbname=test-2", 'root', '');

try {
// prepare select query
$query = "SELECT cat_id, cat_name FROM category WHERE cat_parent_id=:parentid";
$stmt = $con->prepare($query);

// this is the first question mark
$stmt->bindParam(2, $id);

// execute our query
$stmt->execute(array( 'parentid' => $cat_parent_id));

// show the categories one by one
while($c = $stmt->fetch(PDO::FETCH_ASSOC)){
    $output .= '<option value=' . $c['cat_id'] . '>' . $indent . $c['cat_name'] . "</option>\n";
    if($c['cat_id'] != $cat_parent_id){

        CategoryTree($output, $c['cat_id'], $indent . "&nbsp;&nbsp;");
    }
}
// return the list of categories
return $output;
 }
  // show error
    catch(PDOException $exception){
   die('ERROR: ' . $exception->getMessage());
   }
    }

和HTML:

<td><select name="category" id="category" required="">
 <option value='0'>Select the category</option>

 <?php

   echo CategoryTree();
 ?>  
     </select>
  </td>

我希望当html选择中cat_parent_id = 0时,cat_name不可点击,只需将其显示为粗体。如果cat_parent_id> 0仍然可以选择进入html选择。

我该怎么做?谢谢

php mysql pdo
1个回答
0
投票

您必须更改以下代码:

while($c = $stmt->fetch(PDO::FETCH_ASSOC)){
    $output .= '<option value=' . $c['cat_id'] . '>' . $indent . $c['cat_name'] . "</option>\n";
    if($c['cat_id'] != $cat_parent_id){

        CategoryTree($output, $c['cat_id'], $indent . "&nbsp;&nbsp;");
    }
}

至 :

while($c = $stmt->fetch(PDO::FETCH_ASSOC)){
$disable= "";
if($cat_parent_id==0 ){
        $disable= 'disabled="disabled"';
    }
    $output .= '<option  '. $disable.'  value=' . $c['cat_id'] . '>' . $indent . $c['cat_name'] . "</option>\n";
    if($c['cat_id'] != $cat_parent_id){

        CategoryTree($output, $c['cat_id'], $indent . "&nbsp;&nbsp;");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.