svivian Posted March 1, 2008 Share Posted March 1, 2008 If I want to display, say, data from a database in an HTML table, I'd normally run the query then use a while loop listing a table row and its cells for each tuple returned from the database. But if I wanted to display a similar table (same structure but different data) on a different page, I'd have to repeat code. What is the best way for limiting this duplicate code? At the moment I can think of two ways: - set up a global function that displays the data and call it on each iteration - store a HTML/PHP "snippet" in another file and include it on each iteration I'm guessing the include method isn't going to be very fast. Are there any better ways? Quote Link to comment Share on other sites More sharing options...
haku Posted March 1, 2008 Share Posted March 1, 2008 Either one will work. I would use a function myself. Quote Link to comment Share on other sites More sharing options...
QuietWhistler Posted March 1, 2008 Share Posted March 1, 2008 You can make a function like this: function createTable( $col_names, $field_names ) { print( "<table><tr>" ); for( $i = 0; $i < sizeof( $col_names ); $i++ ) { print( "<td>" . $col_names[ $i ] . "</td>" ); } print( "</tr>" ); //mysql query code omitted while( $temp = mysql_fetch_array( $result ) ) { print( "<tr>" ); for( $i = 0; $i < sizeof( $field_names ); $i++ ) { print( "<td>" . $temp[ $field_names[ $i ] ] . "</td>" ); } print( "</tr>" ); } print( "</table>" ); } Then you'd call the function like this: $col_names = array( "column name 1", "column name 2", "column name3" ); $field_names = array( "db_name1", "db_name2", "db_name3" ); createTable( $col_names, $field_names ); But you have to be sure that the amount of elements in $col_names is the same as the amount of elements in $field_names Quote Link to comment Share on other sites More sharing options...
shocker-z Posted March 1, 2008 Share Posted March 1, 2008 I would say create a function with it in kind of like below (untested) function getdata($query) { $query=mysql_query($query); echo '<table>'; while($row=mysql_fetch_array($query)) { echo 'Your HTML and php variables here'; } echo '</table>'; } Regards Liam Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.