首页 > 解决方案 > 来自数据库的类别树。仅可点击 cat_parent_id> 0

问题描述

我有这个脚本来从数据库中获取类别树并在 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 选择。

我该怎么做?谢谢

标签: phpmysqlpdo

解决方案


您必须更改以下代码:

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

推荐阅读