难倒在PHP循环中间

时间:2009-07-31 18:43:01

标签: php mysql loops while-loop

这是我到目前为止所得到的 -

$awards_sql_1 = mysql_query('SELECT * FROM categories WHERE section_id = 1') or die(mysql_error());
$awards_sql_2 = mysql_query('SELECT * FROM categories WHERE section_id = 2') or die(mysql_error());
$awards_sql_3 = mysql_query('SELECT * FROM categories WHERE section_id = 3') or die(mysql_error());
$awards_sql_4 = mysql_query('SELECT * FROM categories WHERE section_id = 4') or die(mysql_error());

$loop = 1;

while($row_sections = mysql_fetch_array($sections_query)) {
    $category = 1;
    echo "<h3>" . $row_sections['section_name'] . " (Loop# $loop)</h3>";

    while($categories = mysql_fetch_array(${"awards_sql_{$loop}"})) {
        ${"winners_sql_{$loop}"} = mysql_query("SELECT * FROM 2009_RKR_bestof WHERE section = $loop && category = $category ORDER BY result_level ASC") or die(mysql_error());
        echo "<h4><strong>{$categories['category_name']}</strong></h4>";
        echo "<ul class=\"winners\">";
>>          while($winners = mysql_fetch_array(${"winners_sql_{$loop}"})) {
                switch ($winners['result_level']) {
                    case 1: $result_level = "Platinum"; break;
                    case 2: $result_level = "Gold"; break;
                    case 3: $result_level = "Silver"; break;
                }
                if (isset($winners['url'])) { $anchor = "<a href=\"http://{$winners['url']}\" target=\"_blank\">"; $close = "</a>"; }
                echo "<li>$anchor{$winners['winner']}$close ($result_level)</li>";

                unset($anchor);
                unset($close);
            }
        echo "</ul>";
        $category++;
    }
    $loop++;
}

我感到困难的是,我正在让这个东西正确循环,我的循环计数器($ loop)正在工作,但是当它有时间吐出第一个循环通过获胜者后的实际奖励收件人,它只生成类别标题,列表项目没有被淘汰。

我添加了一个小指针指向我认为问题开始或居中的位置(&gt;&gt;)。

我的猜测是我需要在某处取消var,但我不知道,我看不到它。

2 个答案:

答案 0 :(得分:3)

我使用的是KM - 您正在显示单个页面并且使用循环,您会立即发生大量查询 - 如果有1,000个人同时点击该页面会怎么样?哎哟...

也许考虑一个更大的查询(带有一些重复的数据)并循环一次?

例如:

SELECT 
  section_name, 
  category_name,
  result_level,
  url,
  winner
FROM 2009_RKR_bestof
INNER JOIN categories ON 2009_RKR_bestof.category = categories.id
INNER JOIN sections ON 2009_RKR_bestof.section = sections.id
ORDER BY section_name,category_name ASC

在你的循环中,你可以做检查以确定你是否在新的部分(类别/等等):

//pseudo-code
$current_section = "";
while($stuff = mysql_fetch_array($sql))
{
  if ($current_section == "")
  {
    $current_section = $stuff["section_name"];
  }
  if ($current_section == $stuff["section_name"])
  {
    //keep going in your loop
  }
  else
  {
    //we've gotten to a new section - so close your html and start a new section
  }
}

你明白了......

答案 1 :(得分:0)

我的猜测是这是一个数据问题。阅读标题没有问题,只有获奖者。如果迭代一次,我会检查数据,并确保winners_sql_2 - winnders_sql_4获取实际数据。也许添加echo winners_sql_2行,输出查询内容,并确保查询框架正确。