从数据库获取类别到 HTML Optgroups 和 PHP 中的选项
我试图从数据库中获取我的类别,并将其子类别放入 和
标签中,我希望父级为
< optgroup>
标签,但我无法循环遍历所有级别,我只能到达级别 2,而且不能走得太远!
这是我到目前为止得到的:
$con = mysql_connect($dbHost, $dbUsername, $dbPassword);
if (!$con) {
echo "Cannot connect to the database: " . mysql_error();
exit;
}
$db_selected = mysql_select_db($dbName, $con);
if (!$db_selected) {
echo "Can\'t use $dbName : " . mysql_error();
exit;
}
$query = "SELECT * FROM categories";
$result = mysql_query($query);
$pidHolder = null; // To take the current parent pid in the loop
$optOpen = false; // Check that optgroup tag is opened
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($line['parent_id'] == 0 && $line['cat_id'] == 0)
continue;
if ($line['parent_id'] == 0) {
if ($optOpen) {
echo '</optgroup>';
$optOpen = false;
}
echo "<optgroup value=" . $line['cat_name'] . "\" label=\"" . $line['cat_name'] . "\">";
$pidHolder = $line['cat_id'];
$optOpen = true;
continue;
} else if (isset($pidHolder) && $pidHolder == $line['parent_id']) {
echo '<option value="' . $line['cat_id'] . '">' . $line['cat_name'] . '</option>\n';
continue;
}
}
mysql_close();
我的代码有什么问题?我需要遍历其余的孩子什么?
I am trying to get my categories from the database with their subcategories into <optgroup>
and <option>
tags and I want the parents to be <optgroup>
tags but I can't loop through all the levels, I only get to level 2 and I can't get too far!
This is what I got so far:
$con = mysql_connect($dbHost, $dbUsername, $dbPassword);
if (!$con) {
echo "Cannot connect to the database: " . mysql_error();
exit;
}
$db_selected = mysql_select_db($dbName, $con);
if (!$db_selected) {
echo "Can\'t use $dbName : " . mysql_error();
exit;
}
$query = "SELECT * FROM categories";
$result = mysql_query($query);
$pidHolder = null; // To take the current parent pid in the loop
$optOpen = false; // Check that optgroup tag is opened
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($line['parent_id'] == 0 && $line['cat_id'] == 0)
continue;
if ($line['parent_id'] == 0) {
if ($optOpen) {
echo '</optgroup>';
$optOpen = false;
}
echo "<optgroup value=" . $line['cat_name'] . "\" label=\"" . $line['cat_name'] . "\">";
$pidHolder = $line['cat_id'];
$optOpen = true;
continue;
} else if (isset($pidHolder) && $pidHolder == $line['parent_id']) {
echo '<option value="' . $line['cat_id'] . '">' . $line['cat_name'] . '</option>\n';
continue;
}
}
mysql_close();
What's the problem with my code? and what do I need to loop through the rest of children?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用递归函数来轻松管理您的类别并将它们放入
和
中。
try to use a recursive function in order to easily manage your categories and putting them in a
<optgroup>
and<option>
.