我有这个脚本从数据库中获取类别树并在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 . " ");
}
}
// 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选择。
我该怎么做?谢谢
您必须更改以下代码:
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 . " ");
}
}
至 :
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 . " ");
}
}