将查询结果转换为HTML列表

时间:2012-06-28 09:58:45

标签: php mysql

我真的只是把我的脚趾浸入PHP和MySQL水域。我已经按照我想要的方式完成了这项工作,但我知道这很丑陋,我想知道如何真正了解他们正在做什么的人会这样做。

    function displayCategoryMenu($db){  
       echo '<ul class="class">';
       foreach($db->query('SELECT * FROM categoryDb, thingDb WHERE category = category AND categoryId= "aaa0001"  ORDER BY category, thingName') as $row){
          if($categoryName!== $row['categoryName']){
            $categoryName= $row['CategoryName'];
            echo '<li class="category">'.$categoryName.'</li>';
          }
          echo'<li><a class="fader" href="?&amp;page='.$row['thingId']">'.$row['thingName'].'</a></li>';
      }
      echo '</ul>';

       echo '<ul class="class">';
       foreach($db->query('SELECT * FROM categoryDb, thingDb WHERE category = category AND categoryId= "aaa0002"  ORDER BY category, thingName') as $row){
          if($categoryName!== $row['categoryName']){
            $categoryName= $row['CategoryName'];
            echo '<li class="category">'.$categoryName.'</li>';
          }
          echo'<li><a class="fader" href="?&amp;page='.$row['thingId']">'.$row['thingName'].'</a></li>';
      }
      echo '</ul>';
      $db=null;
    }

这基本上会产生一个无序的列表菜单,其中第一个孩子充当标题:

    <ul>
       <li>category1Name</li>
       <li><a>thing</a></li>
       <li><a>thing</a></li>
       <li><a>thing</a></li>
    </ul>
    <ul>
       <li>category2Name</li>
       <li><a>thing</a></li>
       <li><a>thing</a></li>
       <li><a>thing</a></li>
    </ul>

或:

组别

  • 事情
  • 事情

类别2

依此类推......

每个ul代码的唯一区别是“categoryId”(aaa0001,aaa0002等等)我只能想象我会用最难的方式来解决这个问题。我很想知道应该怎么做。

4 个答案:

答案 0 :(得分:2)

您应该将类​​别ID列表存储在数组中的某个位置,在使用变量代替类别ID时对其进行迭代。类似的东西:

function displayCategoryMenu($db){  
    $categoryIds = array('aaa0001', 'aaa0002');

    foreach ($categoryIds as $categoryId) {
        echo '<ul class="class">';
        foreach($db->query('SELECT * FROM categoryDb, thingDb WHERE category = category AND categoryId= "' . $categoryId . '"  ORDER BY category, thingName') as $row) {
            if($categoryName !== $row['categoryName']){
                $categoryName = $row['CategoryName'];
                echo '<li class="category">' . $categoryName . '</li>';
            }
            echo '<li><a class="fader" href="?&amp;page=' . $row['thingId'] . '">' . $row['thingName'] . '</a></li>';
        }
        echo '</ul>';
    }
}

此处数组$categoryIds包含您必须显示的ID列表,您可以动态生成它或将其作为函数参数传递,它可以轻松扩展。 foreach循环遍历此数组的每个元素,并为循环中$categoryId变量表示的每个ID执行完全相同的HTML显示和SQL查询作业。

关于$db = null;行的

旁注:如果您未传递$db函数参数as a reference,则修改其在你的函数中,你做的方式不会对原始变量产生任何影响,这一行是不必要的。

答案 1 :(得分:1)

使用您所做的相同功能,我会同时选择所有类别和事物,如下所示:

function renderCategoryMenus($db, $category_id_array)
{  
   // Convery array('a00','b00') to string "'a00','b00'"
   $category_ids = "'" . implode("','", $category_id_array) "'";

   // Change * to just the fields you need
   // Use a join
   // WHERE id IN ('a00','b00')

   $query = 
      'SELECT CategoryName, thingName 
      FROM categoryDb 
      INNER JOIN thingDb 
      ON categoryDb.category = thingDb.category 
      WHERE categoryId IN \''. $category_ids .'\'  
      ORDER BY category, thingName'; 

   $results = $db->query($query);

   // Initialize your variables
   $output = '';
   $categoryName = '';

   foreach($results as $row) 
   {
      if ($categoryName != $row['categoryName']) // If this is a new category
      {
         if ($categoryName != '') // And it is NOT the first new category
         {
            $output .= '</ul>'; // End off the previous category
         }         

         $categoryName = $row['CategoryName'];

         // Store your output into a variable so you can return it
         $output .= '<ul class="class"><li class="category">' . 
            $categoryName . '</li>';
      }

      $output .= '<li><a class="fader" href="?&amp;page=' . 
         $row['thingId'] . '>' . $row['thingName'] . '</a></li>';
   }

   // End off the last category
   if ($output != '') // If we had any categories whatsoever
   {
      $output .= '</ul>';
   }

    return $output;
}    

echo renderCategoryMenus($db, array('aaa0001', 'aaa0002'));

更简单的方法是使用像Yii那样的对象关系映射器。

使用Yii,你可以做一些简单的事情:

function renderCategoryAsMenu($category)
{  
   $output .= '<ul class="class"><li class="category">' . 
      $categoryName . '</li>';      

   // This bit actually selects all 'things' in this 'category'
   foreach ($category->things as $thing)   
      $output .= '<li><a class="fader" href="?&amp;page=' . 
         $thing->thingId . '>' . $thing->thingName . '</a></li>';
   }

   $output .= '</ul>';

    return $output;
}    

$category_keys = array('a00','b00');
$categories = Category::model()->findAllByPk($category_keys);

$output = '';
foreach ($categories as $category)
{
   $output .= renderCategoryAsMenu();
}
echo output;

你甚至可以在模型上使renderCategoryAsMenu成为一个函数,在这种情况下你可以说$category->renderAsMenu()

答案 2 :(得分:0)

取决于您希望显示的类别ID:

我建议1个查询并循环遍历结果集。

那将是

1)没有WHERE clausule(除非你需要它用于连接,因为你有2个WHERE条件)

SELECT * FROM categoryDb, thingDb ORDER BY category, thingName

2)或扩展WHERE

WHERE categoryId="aaa001" OR categoryId="aaa002" ...

我还建议:

if($categoryName!== $row['categoryName'])
{
    echo '<li class="category">' . $row['CategoryName'] . '</li>';
}

您可以将该功能重命名为“writeCategoryMenu”。

答案 3 :(得分:0)

尝试这样的事情..我认为这更容易...... 为了调试我建议你使用ie $sql_query

<?php
function displayCategoryMenu($db){  

    $sql_query  =  'SELECT * FROM 
                        categoryDb 
                    LEFT JOIN thingDb
                        ON categoryDb.category = thingDb.category
                    WHERE
                        thingDb.visible = 1                     
                    ORDER BY 
                        thingDb.category ASC, 
                        thingDb.thingName';

    $result = $db->query($sql_query);
    if(!mysql_error()){

    foreach ($result as $row) {
        if($currentcategory <> $row['CategoryName']){
            $output .=  '<ul class="class">';
            $output .=  '   <li class="category">'.$categoryName.'</li>';
            $output .=  '   <li><a class="fader" href="?&amp;page='.$row['thingId'].'">'.$row['thingName'].'</a></li>';
            $output .=  '</ul>';
        } else {
            $output .=  '<li><a class="fader" href="?&amp;page='.$row['thingId'].'">'.$row['thingName'].'</a></li>';
        }

        $currentcategory = $row['CategoryName'];

    }
    }else{
        $output = mysql_error().'<br>QUERY: '.$sql_query;
    }

    echo $output;

?>