php - 来自数据库的类别树。仅可点击 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 . " ");
}
}
// 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 . " ");
}
}
推荐阅读
- jmeter - JMeter 参数化 $URL
- terraform - oci-terraform "remote-exec" 脚本作为 root 用户
- sql - 对多个值进行分组的 SQL 查询
- angular - 获取单选按钮的值,它发送“on”而不是实际值
- javascript - 将 blob URL 上传到 Imgur?
- javascript - 即使更改了哈希值,如何在网页中单击浏览器后退按钮时返回上一页?
- key-generator - Keygens如何运作?
- json - 加特林登录 Json
- angular - 具有自定义列的自定义 Angular 6 材质表组件
- javascript - JestJS:如何测试嵌套(异步)函数中的调用函数