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

时间:2019-02-28 10:24:28

标签: php mysql pdo

我有这个脚本来从数据库中获取类别树,并以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 select中的cat_parent_id = 0时,cat_name不可点击,只需将其显示为粗体即可。 如果cat_parent_id> 0仍然可以选择进入html select。

我该怎么办? 谢谢

1 个答案:

答案 0 :(得分: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;");
    }
}