从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?

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
}
?>
<?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 if($flagrow['flag1']!='') echo $flagrow['flag1']; ?></p>
<p><?php if($flagrow['flag2']!='') echo $flagrow['flag2']; ?></p>
<p><?php if($flagrow['flag3']!='') echo $flagrow['flag3']; ?></p>
<p><?php if($flagrow['flag4']!='') echo $flagrow['flag4']; ?></p>
</div>
  <?php
}
?>

check if variable is empty then it comes in if else not