Jump to content


Photo

Dynamic HTML Table from MySql query problem *SOLVED*


  • Please log in to reply
2 replies to this topic

#1 cyprus

cyprus
  • Members
  • PipPipPip
  • Advanced Member
  • 68 posts

Posted 24 September 2006 - 09:15 AM

Can someone spot why this is not working properley. Its supposed to dynamically create an HTML table from a database query. But the columns are getting repeated, and the captions are misplaced. Many thanks

<?php
if (($result)||(mysql_errno == 0)) 
{ 

echo "<table border='1' bordercolor='#000000' bgcolor='#FFFFCC' width='80%'><tr>"; 

  if (mysql_num_rows($result)>0) 
  { 
          //loop thru the field names to print the correct headers 
          $i = 0; 
          while ($i < mysql_num_fields($result)) 
          { 
       echo "<td align='left'>". mysql_field_name($result, $i) . "</td>"; 
       //
$i++; 
    } 
    echo "</tr>"; 
    
    //display the data 
    while ($rows = mysql_fetch_array($result)) 
    { 
      echo "<tr>"; 
      foreach ($rows as $data) 
      { 
        echo "<td align='center'>". $data . "</td>"; 
      } 
    } 
  }else{ 
    echo "<tr><td colspan='" . ($i+1) . "'>No Results found!</td></tr>"; 
  } 
  echo "</table>"; 
}else{ 
  echo "Error in running query :". mysql_error(); 
} 
?> 

MOD EDIT code tags added

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 24 September 2006 - 10:06 AM

Use mysql_fetch_assoc() instead of mysql_fetch_array()

By default, fetch array gets the values twice, numeric index and fieldname index
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 cyprus

cyprus
  • Members
  • PipPipPip
  • Advanced Member
  • 68 posts

Posted 24 September 2006 - 10:15 AM

Many thanks Barand, mysql_fetch_assoc($result) fixed my problem. Best regards




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users