开发者

How to write this loop prettier?

I've just read this topic highlight search keywords on hover and actually I use pre开发者_如何学编程tty the same structure, but it looks awful. So can you give me an advice, how to write this loop prettier in one php file, I mean php and html at the same time?

<table class="result">
    <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) {
    $cQuote =  highlightWords(htmlspecialchars($row['cQuotes']), $search_result);
    ?>
    <tr>
    <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td>
    <td style="font-size:16px;"><?php echo $cQuote; ?></td>
    <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td>
    <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td>
    </tr>
<?php } ?>


Personally I would keep the HTML section for printing out values only, not doing database connections, calling functions, and so on. Something like this:

<?php
$rows = array();
while ($row= mysql_fetch_array($result, MYSQL_ASSOC))
{
    $row['cquote_hi'] = highlightWords(htmlspecialchars($row['cQuotes']), $search_result);
    $rows[] = $row;
}
?>

<table class="result">
    <?php foreach ( $rows as $row ) : ?>
    <tr>
    <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td>
    <td style="font-size:16px;"><?php echo $row['cquote_hi']; ?></td>
    <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td>
    <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td>
    </tr>
    <?php endforeach; ?>
</table>

If your server setup allows it, you can echo variables with short tags: <?=$row['cquote_hi']?>

I don't know what the h() function is doing but you could perhaps call it for each variable in the original while loop, then just echo the variables.


This would be my way:

<?

echo '<table class="result">';

while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) {

    $cQuote =  highlightWords(htmlspecialchars($row['cQuotes']), $search_result);

    echo '
    <tr>
        <td style="text-align:right; font-size:15px;">'.h($row["cArabic"]).'</td>
        <td style="font-size:16px;">'.$cQuote.'</td>
        <td style="font-size:12px;">'.h($row["vAuthor"]).'</td>
        <td style="font-size:12px; font-style:italic; text-align:right;">'.h($row["vReference"]).'</td>
    </tr>';
}

echo '</table>';

?>

All php...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜