我试图从下拉列表中显示用户选择子类别并显示他的父类别,但我的代码显示显示直到第二级父类别我在php中的新功能帮助我,谢谢你
显示所有类别
<form action="action/update-category.php" method="post" class="form-horizontal">
<fieldset>
<?php
include_once './action/connection.php';
?>
<?php
$id = $_GET['id']; //
$parentId = $_GET['parentId'];
$sql = "SELECT * FROM category WHERE id = $id";
$result = mysqli_query($mysqli, $sql);
$mainCategories = array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$mainCategories[] = $row;
}
} else {
echo "0 results";
}
// echo "<b>Thank you! Record UPDATED Successfully!";
?>
<!-- Form Name -->
<legend>Edit Product</legend>
<div class="col-md-12">
<div class="form-group" id="category_main">
<label class="col-md-6 control-label" for="product_categorie">CATEGORY</label>
<div class="col-md-6">
<select for="category_main" onchange="loadChildCategories(this);" id="" name="mainCategory_1" class="form-control category_main">
<option> Please select parent category</option>
<?php
foreach ($mainCategories AS $eachCategory) {
echo "<option value='".$eachCategory['parentId']."'>".$eachCategory['name']."</option>";
}
?>
</select>
</div>
</div>
</div>
我得到了parentid和id并将其发送到更新页面,
更新-category.php
<?php
include_once 'connection.php';
if(!empty($_POST["parentId"])) {
$id = $_POST['parentId'];
$sql = "SELECT * FROM category WHERE id='".$id."' Or parentId = '0'";
$result = mysqli_query($mysqli, $sql);
$childCategories = array();
$response = array();
if (mysqli_num_rows($result) > 0) {
$response['hasChildCategories'] = true;
$htmlChildCategories = '<div class="form-group" id="category_'.$id.'">
<label class="col-md-6 control-label" for="product_categorie">CATEGORY</label>
<div class="col-md-6">
<select for="category_'.$id.'" onchange="loadChildCategories(this)" name="mainCategory_'.$id.'" class="form-control category_main">
<option value="'.$id.'"> Select parent category</option>';
// output data of each rowa
while($row = mysqli_fetch_assoc($result)) {
$childCategories[] = $row;
$htmlChildCategories .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
$htmlChildCategories .= '</select></div></div>';
$response['html'] = $htmlChildCategories;
}
else
{
$response['hasChildCategories'] = false;
$response['html'] = '';
}
echo json_encode($response);
}
?>
更新类别ID
maven {
url "https://maven.google.com"
}
答案 0 :(得分:4)
实际上,您的Update-category.php代码存在问题,您只选择所选类别的父类别。您必须编写递归函数来获取所有上述父类别。
如果您提供了loadChildCategories()的定义,那么它很容易回答您。但您仍然可以查看以下网址,这对您有所帮助。
How can I recursively get the IDs of all the parent elements in a multidimensional array?
由于