dongluan7821 2015-05-29 11:24
浏览 30
已采纳

从PDO查询循环内部循环

Consider a situation where you have a mysql table FLAGS with a random amount of rows

ID  Language   Flag1               Flag2              Flag3             Flag4 
1   dutch      flanders_flag.png   dutch_flag.png 
2   french     wallonia_flag.png   french_flag.png    morocco_flag.png     
3   english    england_flag.png    ireland_flag.png   america_flag.png  scotland_flag.png

if i want to query these rows and put them into my html i use the while loop because i never know how much rows this table FLAGS has.

<?php
   $flagquery = $db->prepare ("SELECT * FROM flags");
   $flagquery->execute();
   while ($flagrow = $flagquery->fetch(PDO::FETCH_ASSOC)) {
?>
  <div class="col-md-1 col-sm-2 col-xs-6"> 
    <p><?php echo $flagrow['language']; ?></p>
    <p><?php echo $flagrow['flag1']; ?></p>
    <p><?php echo $flagrow['flag2']; ?></p>
    <p><?php echo $flagrow['flag3']; ?></p>
    <p><?php echo $flagrow['flag4']; ?></p>
  </div>
<?php
  }
?>

But as you can see in the FLAGS table you don't always have 4 flags a language so i would think you have to do a while loop inside this previous while loop to echo only the flags that are present in the FLAGS table instead of just echo all the flags even if they are empty.

Are my thoughts right? Or what would be the best way to handle my situation?

  • 写回答

2条回答 默认 最新

  • dougan1330 2015-05-29 11:29
    关注

    No you don't need a second loop , you can use !empty() . it will return false if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable . it will be useful in your case and in case you allow FLAGS to have NULL value.

    <?php
     $flagquery = $db->prepare ("SELECT * FROM flags");
     $flagquery->execute();
     while ($flagrow = $flagquery->fetch(PDO::FETCH_ASSOC)) {
    ?>
    <div class="col-md-1 col-sm-2 col-xs-6"> 
    <p><?php echo $flagrow['language']; ?></p>
    <?php if(!empty($flagrow['flag1'])) echo '<p>'.$flagrow['flag1'].'</p>'; ?>
     <?php if(!empty($flagrow['flag2'])) echo '<p>'.$flagrow['flag2'].'</p>'; ?>
    <?php if(!empty($flagrow['flag3'])) echo '<p>'.$flagrow['flag3'].'</p>'; ?>
    <?php if(!empty($flagrow['flag4'])) echo '<p>'.$flagrow['flag4'].'</p>'; ?>
    </div>
      <?php
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端