Database Code
  Home arrow Database Code arrow Active Table
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
JMSL Numerical Library 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
DATABASE CODE

Active Table
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2004-09-28

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    This table class wraps up a SELECT query and takes care of sorting columns and paging if there are many table rows.

    Sample of use:

    require_once 'activetable.php';

    function FormatDate( $date )
    {
    return substr( $date, 6, 2 ) . "-" . substr( $date, 4, 2 ) . "-" . substr( $date, 0, 4 );
    }

    $table = new ActiveTable(
    "localhost", "authors", "anonymous", "anonymous",
    "select * from news",
    "select count(*) from news",
    2,
    new Column( "Date", create_function( '$row', 'return FormatDate($row["timestamp"]);' ), "timestamp", "*" ),
    new Column( "Author", create_function( '$row', 'return $row["author"];' ),"author", "75%" )
    );

    $table->Display();

    ?>

    By : Atrox

    <?php

    class Tabular
    {
    function Tabular( $widths )
    {
    $this->widths = $widths;
    $this->alternate = 0;
    }

    function begin( $headers )
    {
    echo '<table cellspacing="0" cellpadding="0" border="0" class="widetable">';
    echo '<tr>';
    $i = 0;
    foreach( $headers as $header )
    {
    echo '<td class="rowheader" width="' . $this->widths[$i] . '">' ;
    echo $header;
    echo '</td>';
    $i++;
    }
    echo '</tr>';
    }

    function row( $datas )
    {
    echo "<tr class='row{$this->alternate}'>";
    $this->alternate = 1 - $this->alternate;
    foreach( $datas as $data ) echo "<td>$data</td>";
    echo '</tr>';
    }

    function end()
    {
    echo '</table>';
    }
    }

    class Column
    {
    var $header;
    var $formatter;
    var $width;

    function Column(
    $header, // Header text, e.g. "Author"
    $formatter, // Cell formatter function, e.g. create_function( '$row', 'return $row["author"];' )
    $sortfield, // DB field to use for sorting, e.g. "author"
    $width // Column width, e.g. "*" or "75%"
    )
    {
    $this->header = $header;
    $this->formatter = $formatter;
    $this->width = $width;

    if( $sortfield != false )
    {
    $this->header = "<a href='{$_SERVER['PHP_SELF']}?__sort={$sortfield}'><img border='0' src='img/sort.png'></a>&nbsp;" . $header;
    }
    }

    function format( $row )
    {
    $f = $this->formatter;
    return $f( $row );
    }
    }

    class ActiveTable
    {
    function ActiveTable(
    $host, // Host name, e.g. "localhost"
    $dbname, // Database name, e.g. "mydb"
    $user, // Database user name, e.g. "anonymous"
    $password, // Password, e.g. "mypass"
    $sql, // SQL query, e.g. "select * from news"
    $countsql, // SQL query to count records, e.g. "select count(*) from news"
    $maxrows // max # rows on-screen, 0 for no paging.
    ) {
    // Store instance data.
    $this->host = $host;
    $this->dbname = $dbname;
    $this->user = $user;
    $this->password = $password;
    $this->sql = $sql;
    $this->countsql = $countsql;
    $this->maxrows = $maxrows;

    // Store columns in an array.
    $args = func_get_args();
    for( $i = 0; $i < 7; $i++ ) array_shift( $args );
    $this->columns = array();
    foreach( $args as $arg ) array_push( $this->columns, $arg );
    }

    function Display()
    {
    // Read row offset from POST variables.
    $offset = $_GET["__offset" ];
    if( $offset == null ) $offset = 0;
    if( $offset < 0 ) $offset = 0;

    // Read sort column from POST variables.
    $sort = $_GET["__sort"];

    // Open DB connection.
    $db = mysql_connect( $this->host, $this->user, $this->password );
    mysql_select_db( $this->dbname, $db );

    // Count records in result if paging is on.
    if( $this->maxrows > 0 )
    {
    $result = mysql_query( $this->countsql, $db );
    $row = mysql_fetch_array($result);
    $count = (int) $row[0];
    mysql_free_result( $result );
    }

    // Prepare actual query.
    $query = $this->sql;
    if( $sort != false ) $query .= " ORDER BY " . $sort . " ";
    if( $this->maxrows > 0 ) $query = $query . " LIMIT " . $offset . "," . $this->maxrows;
    $result = mysql_query( $query, $db );

    // Start table.
    $table = new Tabular( array_map( create_function( '$col', 'return $col->width;' ), $this->columns ) );
    $table->begin( array_map( create_function( '$col', 'return $col->header;' ), $this->columns ) );

    // Print table rows.
    while( $row = mysql_fetch_array($result) )
    {
    $strs = array();
    foreach( $this->columns as $col )
    {
    array_push( $strs, $col->format( $row ) );
    }
    $table->row( $strs );
    }

    // Add first/prev/next/last buttons, if required.
    if( $this->maxrows > 0 && ( $offset > 0 || $count - $offset > $this->maxrows ) )
    {
    echo "<tr><td colspan=" . count($this->columns) . ">";
    echo '<table cellpadding="0" cellspacing="0" border="0" width="100%" class="prevnext">';
    echo '<tr>';
    echo '<td align="left">';

    if( $offset > 0 )
    {
    $vars = "__offset=0";
    if( $sort != false ) $vars .= "&__sort={$sort}";
    echo "<a href='{$_SERVER['PHP_SELF']}?{$vars}'><img align='middle' src='img/first.gif'></a>";

    echo "&nbsp;";

    $newoffset = $offset - $this->maxrows;
    $vars = "__offset={$newoffset}";
    if( $sort != false ) $vars .= "&__sort={$sort}";
    echo "<a href='{$_SERVER['PHP_SELF']}?{$vars}'><img align='middle' src='img/prev.gif'></a>";
    }

    echo '</td>';
    echo '<td align="right">';

    if( $count - $offset > $this->maxrows )
    {
    $newoffset = $offset + $this->maxrows;
    $vars = "__offset={$newoffset}";
    if( $sort != false ) $vars .= "&__sort={$sort}";
    echo "<a href='{$_SERVER['PHP_SELF']}?{$vars}'><img align='middle' src='img/next.gif'></a>";

    echo "&nbsp;";

    $newoffset = $count - $this->maxrows;
    $vars = "__offset={$newoffset}";
    if( $sort != false ) $vars .= "&__sort={$sort}";
    echo "<a href='{$_SERVER['PHP_SELF']}?{$vars}'><img align='middle' src='img/last.gif'></a>";
    }

    echo '</td>';
    echo '</tr>';
    echo '</table>';
    echo '</td></tr>';
    }

    $table->end();

    // Delete DB connection.
    mysql_free_result( $result );
    }
    }

    ?>


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Database Code Articles
    More By Codewalkers

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Best practices for software analysis: An introduction to the IBM Rational Software Analyzer application

    This whitepaper presents the benefits of successfully introducing static analysis into your organization using IBM Rational Software Analyzer. Additionally, it identifies some common pitfalls that can hinder the effective use of static analysis tooling as well as presents 10 simple strategies designed to help you quickly realize the value of static analysis using Rational Software Analyzer.
    FREE! Go There Now!


    NEW! Did you say mainframe? e-kit

    Learn how you can extend modern application lifecycle management to IBM System z through the IBM Rational Software Delivery Platform (SDP). The Did you say mainframe? e-kit includes podcasts, webcasts, tutorials, white and red papers, demos, and articles designed to help ease the challenges of modernizing your enterprise. This complimentary kit for mainframe developers is a practical, how-to guide for making the most of an existing development environment, including the skills and infrastructure already in place at an established enterprise.
    FREE! Go There Now!


    NEW! Don't wait! Try the Rational Application Developer (RAD) v7.5 open beta code today

    Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems.
    FREE! Go There Now!


    NEW! Download a free trial of Lotus Quickr 8.0

    Visit IBM developerWorks to download a free trial version of Lotus Quickr 8.0, which enables collaboration by transforming the way everyday business content such as documents, rich media, photos, and video can be shared. Lotus Quickr makes it faster and easier to share content of all types (not just documents) within virtual teams. It is designed to make it easier to collaborate across organizational boundaries, while continuing to work within the context of familiar desktop applications.
    FREE! Go There Now!


    NEW! Evaluate WebSphere Extended Deployment Compute Grid V6.1

    Visit IBM developerWorks to download a free trial version of WebSphere Extended Deployment Compute Grid, which lets you schedule, execute, and monitor batch jobs. Because online transaction processing and batch jobs execute simultaneously on the same server resources, you can avoid costly duplication of resources. Compute Grid supports job types of Java transactional batch, compute-intensive and a new type called "native execution", which enables non-Java workloads to run on distributed end points.
    FREE! Go There Now!


    NEW! IBM Rational ClearCase Innovator's Series

    Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase.
    FREE! Go There Now!


    NEW! Krugle, developerWorks, and code search

    Ken Krugler, co-founder of code search company Krugle, and Laura Merling, vice president of Marketing and Business Development for Krugle, join to talk about the ins and outs of code search and what it means as a new feature for developerWorks users.
    FREE! Go There Now!


    NEW! The dirty dozen: preventing common application-level hack attacks

    As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for People

    Visit IBM developerWorks to try the IBM SOA Sandbox for people. The SOA Sandbox for people provides a trial environment with the necessary tooling and components required to enable consistent human and process interaction and collaboration, showing how you can improve user experience and business productivity.
    FREE! Go There Now!


    NEW! Webcast: IBM Rational Build Forge - Beyond the Build

    The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    DATABASE CODE ARTICLES

    - Examples and Tools for Database Design
    - Relationships, Entities and Database Design
    - Modeling and Designing Databases
    - Data extract to Excel
    - Oracle database class 0.76
    - The opposite of mysql_fetch_assoc
    - On line Thermal Transmitance Calculation
    - pjjTextBase
    - PHP Object Generator
    - FastMySQL
    - RC4PHP
    - SQL function with integrated sprintf()
    - DB Interaction Classes v1.1
    - deeMySQLParser
    - CSV to SQL convertor






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway