matt tuman
matt tuman

Reputation: 83

Displaying data horizontally using php and mysql

Hi I'm attempting to display data retrieved from a mysql table horizontally in an html table using php. The code below works well except for the fact that it leaves out the first record (starts at the second record) in my database. I'm sure it has something to do with the counter but I can't seem to figure out how to get it to stop doing this. If anyone can point out my error I'd really appreciate it!

$items = 5;
$query = "SELECT * FROM members ";

$result = mysql_query($query) 
  or die(mysql_error());

$row = mysql_fetch_array($result);

if (mysql_num_rows($result) > 0) {

echo '<table border="1">';

$i = 0;

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

     $first_name = $row['first_name'];

           if ($i==0) {
                       echo "<tr>\n";
                      }

           echo "\t<td align=\center\">$first_name</td>\n";

           $i++;

           if ($i == $items) {

                              echo "</tr>\n";
                              $i = 0;
                              }
 }//end while loop

 if ($i > 0) {

                 for (;$i < $items; $i++) {
                      echo "<td>&nbsp;</td>\n";
                  }

              echo '</tr>';

              }//end ($i>0) if 

 echo '</table>';

 }else {

   echo 'no records found';
 }

Upvotes: 0

Views: 3238

Answers (4)

DavidMc
DavidMc

Reputation: 1

$row = mysql_fetch_array($result); 1) remove this line of code from ur scripts 2) only use while loop code instead.

Upvotes: 0

James
James

Reputation: 262

I have run into this issue before. Try the do while loop instead. Example

do {

// code

 } while($row = mysql_fetch_array($result)); //end while loop

Upvotes: 0

echo_Me
echo_Me

Reputation: 37233

try this simpler.

       $items = 5;
  $query = "SELECT * FROM members ";

 $result = mysql_query($query) or die(mysql_error());
 if (mysql_num_rows($result) > 0) {

 echo '<table border="1">';
 while($row = mysql_fetch_array($result)){

 $first_name = $row['first_name'];
        echo "<tr>";
       for ($i=0 ; $i <= $items ;$i++) {

                    echo "<td align='center'>".$first_name."</td>";
                    }
}//end while loop
     echo "</tr>";
    echo '</table>';
}else{ echo 'no records found'; }

Upvotes: 1

srakl
srakl

Reputation: 2619

try and remove the 1st

$row = mysql_fetch_array($result);

you are calling it twice, that's why it skips 1 row in your while loop

Upvotes: 1

Related Questions