tags:

views:

925

answers:

5
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");

$i = 1;
while ($row = mysql_fetch_assoc($sql)) {

<p>$i. <?php echo $row['comment'] ?></p>

<div class="border"></div>

$i++;
}

How could I do to not output <div class="border"></div> under the last comment?

+3  A: 
$number = mysql_num_rows($sql);

This will tell you how many rows will be returned. Based on that, you can make sure that the last on does not have the DIV.

WebDevHobo
+2  A: 
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$number = mysql_num_rows($sql);
$i = 1;
   while ($row = mysql_fetch_assoc($sql)) {

   <p>$i. <?php echo $row['comment'] ?></p>

   if($i < $number)
   {
       <div class="border"></div>
    }
   $i++;
}

Using WebDevHobo's suggestion.

Chacha102
A: 
$rslt = mysql_query("SELECT * FROM comments WHERE user = 1");

$i = 1;
if ($row = mysql_fetch_assoc($rslt)) {
  echo '<p>'. $i . ' '. $row['comment'] . '</p>';
  $i++;
  while ($row = mysql_fetch_assoc($rslt)){
    echo '<div class="border"></div>';
    echo '<p>'. $i . ' ' . $row['comment'] . '</p>';
    $i++;
  } // end while
} // end if

Avoids needing to know the number of rows. Executes the if statement only once instead of each loop. The HTML and php were kind of messy and inconsistent, so I just assumed the whole block was within php tags. Obviously, open and close the php tag as you see fit.

This is largely a style issue, but I decided that the variable name $sql was a bit misleading, as it is often and commonly used to hold the string of the sql statement to be executed, I therefore changed the variable name to $rslt.

Scott
+5  A: 
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$output = array ();
while ($row = mysql_fetch_assoc($sql)) {
  $output[] = $row['comment'];
}
echo join('<div class="border"></div>', $output);
dpk
+1  A: 
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");

$i = 1;
while ($row = mysql_fetch_assoc($sql)) {

$out_data[] = "<p>$i {$row['comment']} </p>";

$i++;
}

$divider = '<div class="border"></div>';
$output = implode ($divider, $out_data);

echo $output;
Alex L