从 PHP/MYSQL 选择值填充下拉菜单。如何重新排列输出

Posted

技术标签:

【中文标题】从 PHP/MYSQL 选择值填充下拉菜单。如何重新排列输出【英文标题】:Populating Drop Down Menu from PHP/MYSQL Select Values. How to rearrange output 【发布时间】:2013-11-01 23:17:51 【问题描述】:

我将继续展示当前 html 输出的外观,下面的同一个小提琴是我希望输出 HTML 的方式:http://jsfiddle.net/xQ95X/3/

一切都很好,我只需要这个 jQuery 插件 (Superfish) 的 HTML 结构即可运行。该下拉菜单不适用于 LI 之外的子 UL。它们必须嵌套在里面。

阻止我以这种方式格式化 HTML 的部分如下:

  <ul class="sf-menu">

    <li><a href="#">HOME</a></li>

    <?php

    $sql="SELECT * FROM section ORDER BY orderID";
    $result=mysql_query($sql) or die ("Error!! BAD SELECT SEARCH STATEMENT");
    $nrows = mysql_num_rows($result);

    // Top level Items

    for($i=1;$i<=$nrows;$i++) 
      $row = mysql_fetch_array($result);
      extract($row);

      $sections[] = $section;
      $sectionids[] = $sectionid;

      if ($section == "FORUM") 
        echo"<li><a href='#' rel='dropmenu$i'>$section</a></li>"; 
       else 
        echo"<li><a href='#h' rel='dropmenu$i'>$section</a></li>"; 
      
    

    // Submenu Items


    for($s=0;$s<count($sections);$s++) 

      /*$sm1 = ($s - 1);*/
      $sp1 = ($s + 1);

      $sql3="SELECT * FROM category WHERE sectionid='$sectionids[$s]'";
      $result3=mysql_query($sql3) or die ("Error!! BAD SELECT SEARCH STATEMENT");
      $nrows3 = mysql_num_rows($result3);

      if ($nrows3 > 0) 
        echo"<ul>";
        for($t=0;$t<$nrows3;$t++) 
          $row3 = mysql_fetch_array($result3);
          extract($row3);

          if ($type=='Photo') 
            $title20 = strtolower($title);
            $title20 = str_replace(" ", "_", $title20);
            $sec = strtolower($sections[$s]);
            $sec = str_replace(" ", "_", $sec);
            if ($sec=='photos') 
              echo"<li><a href='" . dirname($_SERVER['PHP_SELF']) . "$sec/$catID-$title20/1.html'>$title</a></li>";
            

            else 
              echo"<li><a href='" . dirname($_SERVER['PHP_SELF']) . "$sec/photos/$catID-$title20/1.html'>$title</li></a>";
            

           elseif ($type=="Contact") 
            $title20 = strtolower($title);
            $title20 = str_replace(" ", "_", $title20);
            echo "<li><a href='" . dirname($_SERVER['PHP_SELF']) . "contactus/contact_$title20.html'>$title</a></li>";
           elseif ($type=='Quote') 

            $sql4="SELECT articleID FROM article WHERE category='49' AND Now() > publishingdate ORDER BY publishingdate DESC LIMIT 0, 1";
            $result4=mysql_query($sql4) or die ("Error! bad select statement");
            $row4=mysql_fetch_array($result4);
            extract($row4);

            echo "<li><a href='" . dirname($_SERVER['PHP_SELF']) . "everton_quotes.php?id=$articleID'>$title</a></li>";
           
          elseif ($type=='LastMatch') 
            $sql4="select r.matchID as matchID2, r.venue, r.versus as versus2, s.year FROM regmatch r, season s WHERE r.season=s.seasonID AND Now() > r.matchdate ORDER BY r.matchdate DESC LIMIT 0,1";
            $result4=mysql_query($sql4) or die ("Error! bad select statement");
            $nrows4=mysql_num_rows($result4);
            if ($nrows4 > 0) 
              $row4=mysql_fetch_array($result4);
              extract($row4);
              if ($venue=='Home') 
                $teams = "Everton V $versus2";
                $teams2 = "everton_vs_" . str_replace(" ", "_", strtolower($versus2));
              
              else 
                $teams = "$versus V Everton";
                $teams2 = str_replace(" ", "_", strtolower($versus2)) . "_vs_everton";
              

              $year = str_replace("/", "-", $year);
              echo "<li><a href='" . dirname($_SERVER['PHP_SELF']) . "match/$year/$matchID2-$teams2/" . strtolower($venue) . "/matchreport.html'>$title</a></li>";
            
           elseif ($type=='NextMatch') 

            $sql5="select r.matchID as matchID3, r.venue, r.versus as versus2, s.year FROM regmatch r, season s WHERE r.season=s.seasonID AND r.matchdate > Now() ORDER BY r.matchdate ASC LIMIT 0,1";
            $result5=mysql_query($sql5) or die ("Error! bad select statement");
            $nrows5=mysql_num_rows($result5);
            if ($nrows5 > 0) 
              $row5=mysql_fetch_array($result5);
              extract($row5);
              if ($venue=='Home') 
                $teams = "Everton V $versus2";
                $teams2 = "everton_vs_" . str_replace(" ", "_", strtolower($versus2));
              
              else 
                $teams = "$versus2 V Everton";
                $teams2 = str_replace(" ", "_", strtolower($versus2)) . "_vs_everton";
              

              $year = str_replace("/", "-", $year);
              echo "<li><a href='" . dirname($_SERVER['PHP_SELF']) . "match/$year/$matchID3-$teams2/" . strtolower($venue) . "/teamnews.html'>$title</a></li>";
            
           else 

    // Overides for missing pages

            if($title == "Gwladys Street Preacher") 
              echo"<li><a href='/fans/121-gwladys_street_preacher/index.html'>$title</a></li>";
             

            elseif($title == "The Secret Fan") 
              echo"<li><a href='/news/124-secret-fan/index.html'>$title</a></li>";
             

            elseif($title == "Toffee Girl") 
              echo"<li><a href='/fans/125-toffee_girl/index.html'>$title</a></li>";
             

            else 

              echo"<li><a href='" . dirname($_SERVER['PHP_SELF']) . $link . "'>$title</a></li>";

            

          

        

        echo"</ul>";
      

    

    echo "</ul>";

    ?>

我希望我已经提供了足够的信息,如果您需要任何其他信息,请告诉我。虽然 JSFiddle 应该让您很好地了解我希望如何输出 HTML。

PS - 我完全知道这不是最干净的代码,我猜它需要大量的重新排列才能获得所需的输出。我愿意接受建议。

【问题讨论】:

你能在sqlfiddle中放一些示例数据吗? 【参考方案1】:

我个人会在第一个循环中嵌套第二个 for 循环(我已更改为 while 循环)(这是非常粗略的代码),但请注意在父循环中已从部分标题中删除。:

一些伪代码:

print parent unordered list start
get section data
loop through section results
    print parent list item start
    print section title
    get page data
    print unordered child list start
    loop through page results
         print child list item start
         print page info
         print child list item end
    print child unordered list end 
    print parent list item end
print parent unordered list end

从伪代码到接近你的代码的东西:

$sql="SELECT * FROM section ORDER BY orderID";
$result=mysql_query($sql) or die ("Error!! BAD SELECT SEARCH STATEMENT");

// Top level Items

while($row = mysql_fetch_array($result)
    extract($row);

    if ($section == "FORUM") echo"<li><a href='#' rel='dropmenu$i'>$section</a>"; 
    else echo"<li><a href='#h' rel='dropmenu$i'>$section</a>"; 

    $sql3="SELECT * FROM category WHERE sectionid='$sectionid'";
    $pageResult=mysql_query($sql3) or die ("Error!! BAD SELECT SEARCH STATEMENT");

    echo "<ul>";
    while($page = mysql_fetch_array($pageResult)
       extract($page);
       //process and print each child <li>...</li> here 
       //(this is a cut down example) where you would add your if/elseif section
       echo "<li>$title</li>";
    
    echo "</ul>"; //close child UL
    echo "</li>"; //close parent LI

【讨论】:

谢谢你,我试试看! :) 无法打印任何内容,空白页。嗯...即使我只是以最低限度的代码使用它。 我确实尝试过输入您的代码,但它什么也没返回。我认为即使不打印子 's 它也会返回*** 's ? 感谢您到目前为止的帮助。我无法让您的框架显示任何内容,您能否指出正确的方向以打印***项目? 我开始明白你做得更好了,虽然你的代码还没有打印任何东西:)【参考方案2】:

我认为您需要将第二个 for 循环嵌套在第一个循环中,以便 ul 标记嵌套在 li 中:一般准则是:

   for($i=1;$i<=$nrows;$i++) 
          $row = mysql_fetch_array($result);
          extract($row);

          $sections[] = $section;
          $sectionids[] = $sectionid;

          if ($section == "FORUM") 
            echo"<li><a href='#' rel='dropmenu$i'>$section</a>";
            for($s=0;$s<count($sections);$s++)  //Filter $sections for FORUM submenu items only
           //submenu items
             
            echo "</li>"; 
           else 
            echo"<li><a href='#h' rel='dropmenu$i'>$section</a>";
            for($s=0;$s<count($sections);$s++)  
           //submenu items
            
            echo </li>"; 
          
        

【讨论】:

【参考方案3】:

我在开发我们公司的网站导航时遇到了同样的问题,提供最佳可扩展解决方案的是所谓的“嵌套集模型”。

Mike hiller 的精彩帖子在这里:

http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

解释了所有并给出了嵌套集合模型的一个很好的总结。这应该是一个很好的起点。

它允许您将所有复杂性放入数据库查询中,并保持数据库表和 php 干净。

基本上,它在数据库中建立一个“类别”表,并使用一个左右值来相互关联并定义它们的层次结构和关系。

是的,只有一张桌子......没有“子类别”表格或任何东西......它们都是平等的并且在一张桌子上。 同样,定义它们的位置和层次结构的是它们的左 (lft) 和右 (rgt) 值。

它会引导您了解如何构建 db 表以及如何布置站点的类别和子类别。这对我来说扩展得很好,每次我发现自己必须添加一个类别时,我所做的就是将它添加到类别表中并更改左右值以适应新类别。

希望这对你和我一样有帮助!

【讨论】:

【参考方案4】:

你需要在里面输入你的第二个选择语句

  if ($section == "FORUM") 
    echo"<li><a href='#' rel='dropmenu$i'>$section</a>";
       //the ul should start here
    echo "</li>"; 
   else 
    echo"<li><a href='#h' rel='dropmenu$i'>$section</a>";
       //the ul should start here
    echo "</li>"; 
  

那么你将不得不避免第二个 for 循环

 for($s=0;$s<count($sections);$s++) 

因为你可以直接在里面获取section id

$sql3="SELECT * FROM articles WHERE id='$sectionid'";

所以在 if 里面写代码然后在 else 里面写代码是不好的。

我对你的代码做了一些修改,希望对你有帮助,第二个 for 循环还没有删除,但我认为它不需要,根据你的要求修改。

<ul class="sf-menu">

<li><a href="#">HOME</a></li>

<?php
$sql="SELECT * FROM section ORDER BY orderID";
$result=mysql_query($sql) or die ("Error!! BAD SELECT SEARCH STATEMENT");
$nrows = mysql_num_rows($result);

// Top level Items

for($i=1;$i<=$nrows;$i++) 
  $row = mysql_fetch_array($result);
  extract($row);

  $sections[] = $section;
  $sectionids[] = $sectionid;

      echo "<li><a href='";

      if ($section == "FORUM")
          echo "#";
      else
          echo "#h";

      echo "' rel='dropmenu$i'>$section</a>";

      for($s=0;$s<count($sections);$s++) 

      /*$sm1 = ($s - 1);*/
      $sp1 = ($s + 1);

      $sql3="SELECT * FROM category WHERE sectionid='$sectionids[$s]'";
      $result3=mysql_query($sql3) or die ("Error!! BAD SELECT SEARCH STATEMENT");
      $nrows3 = mysql_num_rows($result3);

      if ($nrows3 > 0) 
        echo"<ul>";
        for($t=0;$t<$nrows3;$t++) 
          $row3 = mysql_fetch_array($result3);
          extract($row3);

          if ($type=='Photo') 
            $title20 = strtolower($title);
            $title20 = str_replace(" ", "_", $title20);
            $sec = strtolower($sections[$s]);
            $sec = str_replace(" ", "_", $sec);
            if ($sec=='photos') 
              echo"<li><a href='" . dirname($_SERVER['PHP_SELF']) . "$sec/$catID-$title20/1.html'>$title</a></li>";
            

            else 
              echo"<li><a href='" . dirname($_SERVER['PHP_SELF']) . "$sec/photos/$catID-$title20/1.html'>$title</li></a>";
            

           elseif ($type=="Contact") 
            $title20 = strtolower($title);
            $title20 = str_replace(" ", "_", $title20);
            echo "<li><a href='" . dirname($_SERVER['PHP_SELF']) . "contactus/contact_$title20.html'>$title</a></li>";
           elseif ($type=='Quote') 

            $sql4="SELECT articleID FROM article WHERE category='49' AND Now() > publishingdate ORDER BY publishingdate DESC LIMIT 0, 1";
            $result4=mysql_query($sql4) or die ("Error! bad select statement");
            $row4=mysql_fetch_array($result4);
            extract($row4);

            echo "<li><a href='" . dirname($_SERVER['PHP_SELF']) . "everton_quotes.php?id=$articleID'>$title</a></li>";
          
          elseif ($type=='LastMatch') 
            $sql4="select r.matchID as matchID2, r.venue, r.versus as versus2, s.year FROM regmatch r, season s WHERE r.season=s.seasonID AND Now() > r.matchdate ORDER BY r.matchdate DESC LIMIT 0,1";
            $result4=mysql_query($sql4) or die ("Error! bad select statement");
            $nrows4=mysql_num_rows($result4);
            if ($nrows4 > 0) 
              $row4=mysql_fetch_array($result4);
              extract($row4);
              if ($venue=='Home') 
                $teams = "Everton V $versus2";
                $teams2 = "everton_vs_" . str_replace(" ", "_", strtolower($versus2));
              
              else 
                $teams = "$versus V Everton";
                $teams2 = str_replace(" ", "_", strtolower($versus2)) . "_vs_everton";
              

              $year = str_replace("/", "-", $year);
              echo "<li><a href='" . dirname($_SERVER['PHP_SELF']) . "match/$year/$matchID2-$teams2/" . strtolower($venue) . "/matchreport.html'>$title</a></li>";
            
           elseif ($type=='NextMatch') 

            $sql5="select r.matchID as matchID3, r.venue, r.versus as versus2, s.year FROM regmatch r, season s WHERE r.season=s.seasonID AND r.matchdate > Now() ORDER BY r.matchdate ASC LIMIT 0,1";
            $result5=mysql_query($sql5) or die ("Error! bad select statement");
            $nrows5=mysql_num_rows($result5);
            if ($nrows5 > 0) 
              $row5=mysql_fetch_array($result5);
              extract($row5);
              if ($venue=='Home') 
                $teams = "Everton V $versus2";
                $teams2 = "everton_vs_" . str_replace(" ", "_", strtolower($versus2));
              
              else 
                $teams = "$versus2 V Everton";
                $teams2 = str_replace(" ", "_", strtolower($versus2)) . "_vs_everton";
              

              $year = str_replace("/", "-", $year);
              echo "<li><a href='" . dirname($_SERVER['PHP_SELF']) . "match/$year/$matchID3-$teams2/" . strtolower($venue) . "/teamnews.html'>$title</a></li>";
            
           else 

    // Overides for missing pages

            if($title == "Gwladys Street Preacher") 
              echo"<li><a href='/fans/121-gwladys_street_preacher/index.html'>$title</a></li>";
            

            elseif($title == "The Secret Fan") 
              echo"<li><a href='/news/124-secret-fan/index.html'>$title</a></li>";
            

            elseif($title == "Toffee Girl") 
              echo"<li><a href='/fans/125-toffee_girl/index.html'>$title</a></li>";
            

            else 

              echo"<li><a href='" . dirname($_SERVER['PHP_SELF']) . $link . "'>$title</a></li>";

            

          

        

        echo"</ul>";
      

    //end of for

    echo "</li>";
  

// Submenu Items

echo "</ul>";

?>

【讨论】:

已经编辑了ans,实际上为了在我的机器上测试它我已经更改了表名,现在已经将表名编辑为你的,请立即查看【参考方案5】:

看到这个,注意:我添加了一个名为“has_sub”的索引来检查该部分是否有子,然后为它创建一个子菜单

echo '<ul>';
$array = array();
while($row = mysql_fetch_array($query_main_data)) 
    if($row['has_sub'] === 'yes')  
       echo '<li><a>'.$row['section_name'].'</a></li>';
       echo '<ul>';
       while($row2 = mysql_fetch_array($query_sub_data)) 
          echo '<li><a>'.$row['section_name'].'</a></li>';
       
       echo '</ul>';
    

echo '</ul>';

【讨论】:

【参考方案6】:

tl;dr 获取所有数据,然后构建菜单

有很多方法可以做到这一点,而且没有一个是错误的;在我必须这样做的任何地方,我们的 Web 服务器都比数据库服务器多,因此为了更好地扩展,我们尝试最小化数据库调用,并且为了让开发人员更轻松,我们将尽可能多的逻辑提取到数据库之外并完成所有工作php/javascript中的处理。

由于您一开始就知道自己想要什么数据(即,您不必根据传入的某些逻辑或任何东西从数据库中提取不同的东西),您可以在页面的开头,然后构建菜单,而不是在从数据库中提取时尝试这样做。这使您可以 1) 将进行数据库调用的代码和保存用于构建菜单的逻辑的代码分开,以及 2) 将数据库调用减少到仅两个而不是 1 + 部分的数量。根据您的需要,#2 可能不是一个重要因素,但如果您在开始时将所有内容分开,它会更容易阅读。

这样的东西(可能更干净):

<li><a href="#">HOME</a></li>

<?php

$sql="SELECT * FROM section ORDER BY orderID";
$result=mysql_query($sql) or die ("Error!! BAD SELECT SEARCH STATEMENT");
$nrows = mysql_num_rows($result);

// Top level Items

for($i=1;$i<=$nrows;$i++) 
  $row = mysql_fetch_array($result);
  extract($row);

  $sections[$sectionid] = $section; //we want to reference the section by the id later
  $sectionids[] = $sectionid;


// Here we can pull all of the subsections we need
$all_section_ids = implode(',', $sectionids); // join all of the ids with a comma
// SQL IN lets you select all rows where the sectionid matches any of a list
$sql3="SELECT * FROM category WHERE sectionid IN ($all_section_ids)";
$result=mysql_query($sql) or die ("Error!! BAD SELECT SEARCH STATEMENT");
$nrows = mysql_num_rows($result);

for($i=1;$i<=$nrows;$i++) 
  $row = mysql_fetch_array($result);
  extract($row);

  //Whatever values that you need from the category table, depends on what your data looks like
  $subsections[$sectionid][] = $subsection;
  $types[$sectionid][] = $type; //each sectionid gets a separate array
  $some_array[$sectionid][] = $whatever_variable;


//Now we can loop through and create everything
foreach ($sections as $id => $section) 
    //now $section is the name and $id is the sectionid for that section
    echo '<li><a href="whatever link"></a>';
    echo '<ul>';
    //since we separated the subsections by sectionid, we can do this
    foreach ($subsections[$id] as $subsection) 
        echo '<li>';
        //whatever logic you need to to build the inner list
        echo '</li>';
    
    echo '</ul>';

【讨论】:

以上是关于从 PHP/MYSQL 选择值填充下拉菜单。如何重新排列输出的主要内容,如果未能解决你的问题,请参考以下文章

如何根据使用 jQuery/AJAX 和 PHP/MySQL 选择的第一个下拉列表填充第二个下拉列表?

根据第一个选择动态填充第二个下拉菜单

根据另一个下拉列表中的选择填充一个下拉列表,然后重定向

如何验证从 asp.net 中的 SQL 填充的下拉列表(UnobtrusiveValidationMode)错误

在 php mysql 中选择选项时用值填充输入字段

根据下拉值自动填充文本框