質問

I feel like I know this, but am getting frustrated that I can't remember exactly how to do this.

In PHP, I need to repeat items of a record set in a unordered list. I can repeat items fine, but I don't want anything to show if the record set is empty. Right now, if there is no record, the code is still displaying a blank list item, when I just want nothing to appear.

I have tried this:

<?php do { ?>
    <li><a href="#">Content Goes Here</a></li>
<?php } while (!feof($recordsetName) && $row_recordsetName = mysql_fetch_assoc($recordsetName)); ?>

And I have tried doing it this way by putting the repeating element withing an if/else statement like this:

<?php if (!feof($recordsetName)) {
    echo ""; }
else do { ?>
    <li><a href="#">Content Goes Here</a></li>
<?php } while ($row_recordsetName = mysql_fetch_assoc($recordsetName));
; } ?>

But that isn't working either. Any information would be helpful

役に立ちましたか?

解決

while($row = mysql_fetch_assoc($recordsetName)) {
    if($row['fieldname'] != '') {
        echo '<li><a href="#">Content Goes Here</a></li>';
    }
}

or you could check if the query was successful...

$result = mysql_query($sql);
if($result) {
    echo '<li><a href="#">Content Goes Here</a></li>';
}

or if it returned any results...

$results = mysql_fetch_assoc($recordsetName);
if(mysql_num_rows($results) > 0) {
    while($row = mysql_fetch_assoc($results)) {
       echo '<li><a href="#">Content Goes Here</a></li>';
    }
}

Also, you should really be using mysqli or PDO, as mysql is depreciated.

Edit: added loop in example 3.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top