mysql嵌套的php while循环在显示请求的结果之前返回先前的结果

6za6bjd0  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(296)

我正在php中使用双while循环,以分组方式显示mysql数据库的结果。这是我的数据库结构的一个示例:
id姓名团队所在国家
1汉密尔顿梅赛德斯英国
双按钮迈凯轮英国
3阿隆索迈凯轮es
4佩雷斯迈凯轮mx
我希望它像这样分组显示:

  1. ES
  2. Alonso
  3. MX
  4. Perez
  5. UK
  6. Button
  7. Hamilton

但是,我的嵌套循环没有比这更好的了:

  1. ES
  2. Alonso
  3. MX
  4. Alonso
  5. Perez
  6. UK
  7. Alonso
  8. Perez
  9. Button
  10. Hamilton

我的循环在某个地方失败了,或者我只是采取了错误的方法。我尝试了增量、未嵌套循环、重置变量、继续/中断,但我想不通。第一个循环是为每个分组打印一个表结构。这是我的代码示例:

  1. <?php
  2. // count unique country entries
  3. $categories = $db->query("
  4. SELECT DISTINCT country
  5. FROM cms_drivers
  6. WHERE team = '$team'
  7. ORDER BY country
  8. ");
  9. while ($cat = $db->fetch_array($categories)) { // loops 3 times
  10. $custom = $db->query("
  11. SELECT id, name, team, country
  12. FROM cms_drivers
  13. WHERE team = '$team' AND country = '$cat[country]'
  14. ORDER BY name
  15. ");
  16. while ($content = $db->fetch_array($custom)) {
  17. process('$drivers_bits .= "' . fetch_template('cms_drivers_bits') . '";');
  18. }
  19. process('$drivers .= "' . fetch_template('cms_drivers') . '";');
  20. }

是我忽略了一些非常简单的事情,还是这只是一个错误的方法?
cms\u驱动程序\u bits模板:

  1. <tr><td>$content[name]</td></tr>

cms\U驱动程序模板:

  1. <table cellpadding="8" cellspacing="0" width="100%">
  2. <thead>
  3. <tr>
  4. <td class="header">
  5. <span><strong>$cat[country]</strong></span></td>
  6. </tr>
  7. </thead>
  8. <tbody>
  9. $drivers_bits
  10. </tbody>
  11. </table>
k5ifujac

k5ifujac1#

根据你得到的结果,看起来你只需要初始化一下 $drivers_bits 在内部循环之前添加一个空字符串。

  1. $drivers_bits = '';
  2. while ($content = $db->fetch_array($custom)) { ...
  3. ``` `$drivers_bits` 可能用在 `fetch_template('cms_drivers')` ,并且每次都要向其追加值,而不是将其重置为循环迭代的新值。

相关问题