Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write this loop prettier?

Tags:

html

php

mysql

I've just read this topic highlight search keywords on hover and actually I use pretty 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 } ?>

like image 610
good_evening Avatar asked May 28 '10 16:05

good_evening


1 Answers

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.

like image 160
DisgruntledGoat Avatar answered Sep 22 '22 12:09

DisgruntledGoat