简体   繁体   中英

How do I skip an item in while loop if variable empty?

I'm trying to figure out how to skip printing a row from a MySQL table if the variable is empty. For instance, I have a table full of information. I have a while loop that echos the result. How can I skip an entry if a variable is empty?

For instance, can I cancel the echo if 'tweet1' is empty in the row?

mysql_connect ($DBsever, $DBusername, $DBpass) or die ('I cannot connect to the database becasue: '.mysql_error());
mysql_select_db ("$DBname");

$query = mysql_query("SELECT * FROM $DBtable ORDER BY time");

while ($row = mysql_fetch_array($query)) {
    echo "<br /><strong>".$row['time']." ".$row['headline']."</strong><br/>".$row['description']."<br />".$row['story1']." <a href=".$row['link1']." target='_blank'>".$row['link1']."</a> ".$row['tweet1']."<br />";}

You can use continue control structure for skip an iteration. Please read the docs

Example:

if(!$row['tweet']) {
  continue;
}
if (empty($row['tweet'])) {
    continue;
}

你也可能不会在tweet1没有信息的情况下返回行,这会使php检查tweet1中的数据变得不必要。

$query = mysql_query("SELECT * FROM $DBtable WHERE tweet1 IS NOT NULL ORDER BY time");

Try:

while ($row = mysql_fetch_array($query)) {
if ($row['tweet1']) 
    echo "<br /><strong>".$row['time']." ".$row['headline']."</strong><br/>".$row['description']."<br />".$row['story1']." <a href=".$row['link1']." target='_blank'>".$row['link1']."</a> ".$row['tweet1']."<br />";
}
while ($row = mysql_fetch_array($query)) {
  if (!empty($row['tweet1'])    {
    echo "<br /><strong>".$row['time']." ".$row['headline']."</strong><br/>".$row['description']."<br />".$row['story1']." <a href=".$row['link1']." target='_blank'>".$row['link1']."</a> ".$row['tweet1']."<br />";
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM