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
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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.