Jump to content

A good way to display repetitive code


svivian

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/93885-a-good-way-to-display-repetitive-code/
Share on other sites

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.