简体   繁体   中英

how to code an if else dynamic statement

I'm having trouble writing an if else statement. Considering that I've been doing so for years in ColdFusion, this make me feel very stupid.

Here's the task. I need to pull first name, last name, email, co-chair status from a database and return the results. However not everyone has an email, so I need a statement that will include a mailto link for those that have emails, and exclude a mailto link for those that don't.

Here's the code I'm using that includes the mailto link for all.

What adjustments do I need to make? thanks, david

 <?php do { ?>
  <a href="mailto:<?php echo $row_GetMembers['BACmember_Email']; ?>"><?php echo $row_GetMembers['BACmember_First']; ?> <?php echo $row_GetMembers['BACmember_Last']; ?></a>
  <?php /*START_PHP_SIRFCIT*/ if ($row_GetMembers['BACmember_CoChair']=="Yes"){ ?>
    <strong> Co-Chair</strong>
    <?php } /*END_PHP_SIRFCIT*/ ?><br />
<?php } while ($row_GetMembers = mysql_fetch_assoc($GetMembers)); ?>

This is the line of code you want to optionally display as a link (split for readability):

<a href="mailto:<?php echo $row_GetMembers['BACmember_Email']; ?>">
    <?php echo $row_GetMembers['BACmember_First']; ?> 
    <?php echo $row_GetMembers['BACmember_Last']; ?>
</a>

You'll want something like this instead:

<?php if (!empty($row_GetMembers['BACmember_Email'])): ?>
    <a href='mailto:<?php echo $row_GetMembers['BACmember_Email']?>>
        <?php echo $row_GetMembers['BACmember_First']; ?> 
        <?php echo $row_GetMembers['BACmember_Last']; ?>
    </a>
<?php else: ?>
    <?php echo $row_GetMembers['BACmember_First']; ?> 
    <?php echo $row_GetMembers['BACmember_Last']; ?>
<?php endif; ?>

If the email field isn't empty (the ! negates the result, so we're checking if it isn't empty), it prints the first and last name inside an anchor tag. If it is empty, it prints the name without it.

A more elegant solution may be to provide the email address as a separate field or link, as opposed to having a list of some names that are links and some that aren't.

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