Database Code
  Home arrow Database Code arrow PHP form-class generator
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  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
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

PHP form-class generator
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 2
    2003-06-26

    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


    Save yourself some time. Input the DB and table, select the columns you want displayed in the form and go!

    Example usage (generated code was modified a bit):

    mysql_connect(); //INCLUDE your information.. username, password, etc.
    mysql_select_db('testDB'); //CHANGE this line

    session_start();

    $ADMIN_USERNAME='admin';
    $ADMIN_PASSWORD='password';
    $PHP_SELF=$_SERVER['PHP_SELF'];

    class Form_testDB_computers {
    var $TEXTAREA_ROWS=6;
    var $TEXTAREA_COLS=40;
    var $renderStyle=array(
    'computerID'=>'input','make'=>'input','model'=>'input','c_usage'=>'textarea','price'=>'input',
    'short_description'=>'input','long_description'=>'textarea','image'=>'input');
    var $labels=array(
    'computerID'=>'computerID','make'=>'make','model'=>'model',
    'c_usage'=>'usage','price'=>'price','short_description'=>'short_description',
    'long_description'=>'long_description','image'=>'image');

    function generateForm ( $source="",$var2Keep='' )
    {
    $fields = array_keys($this->renderStyle);
    if ( $source == 'request' || $source == 'input' || $source =='form' )
    {
    foreach ( $fields as $n=>$f)
    $$f=$_REQUEST[$f];
    }
    else if ( !empty($source) )
    {
    //$source should be a mySQL string
    $query = mysql_query($source);
    $data = mysql_fetch_array($query);

    //Begin conversion from DB row to our form variables
    foreach ( $fields as $n=>$f)
    $$f=$data[$f];
    }

    echo "";
    echo "";
    echo "";
    //Time to render the form itself, now that we have the variables;
    foreach ( $fields as $n=>$f )
    {
    echo "";
    }
    echo "
    ".$this->labels[$f]."";
    switch($this->renderStyle[$f])
    {
    case 'textarea':
    echo "";
    break;

    case 'input':
    default:
    echo "";
    }
    echo "
    ";
    }

    function verifyForm ()
    {
    foreach ( $this->renderStyle as $f=>$r)
    if ( empty($_REQUEST[$f]) )
    return false; //At least one empty element

    return true;
    }

    function getSQL_setClause ()
    {
    $c=0;
    $ret="";
    foreach ($this->renderStyle as $f=>$r)
    {
    if ( $c++ > 0 )
    $ret .= ",";
    $ret .= "$f='$_REQUEST[$f]'";
    }
    return $ret;
    }

    function getSQL_updateRow ( $whereClause)
    {
    $sql = "update computers set " .$this->getSQL_setClause() . " where $whereClause";
    return $sql;
    }

    function getSQL_insertRow ()
    {
    $sql = "insert into computers set " . $this->getSQL_setClause();
    return $sql;
    }

    } //End Class

    function showMainMenu ()
    {
    global $form;

    if ( isset($_REQUEST['compID']) )
    {
    ob_start();
    $compID = $_REQUEST['compID'];
    if ( $_SESSION['loggedIn'] )
    {
    if ( isset($_REQUEST['submitted']) )
    {
    if ( $form->verifyForm() )
    {
    $sql = $form->getSQL_updateRow('computerId='.$compID);
    if ( mysql_query($sql) )
    echo "Computer info updated

    ";
    }
    else
    $form->generateForm('form','compID');
    }
    else
    $form->generateForm("select * from computers where computerId=$compID",'compID');
    }
    else
    {
    echo "Please log-in first to edit data

    ";
    }
    $printLater = ob_get_contents();
    ob_end_clean();

    $info = mysql_fetch_array(mysql_query("select * from computers where computerId=$_REQUEST[compID]"));
    echo "

    $info[short_description]

    ".nl2br($info[long_description])."

    Usage: $info[c_usage]
    Price: $info[price]
    Make: $info[make]
    Model: $info[model]

    ";
    echo $printLater;
    }
    else
    {
    //Show all available computers
    $sql = mysql_query("select * from computers order by computerID desc");
    while ( $row = mysql_fetch_array($sql) )
    {
    echo "$row[short_description]
    ";
    }
    echo "
    Insert new computer";

    if ( !$_SESSION['loggedIn'] )
    {
    echo "

    Log-in";
    }
    else
    echo "

    Logged in as admin";
    }
    }

    $form = new Form_testDB_computers();

    //print_r($_REQUEST);

    if ($_REQUEST['process'] == 'insert' )
    {
    if ( isset($_REQUEST['submitted']) )
    {
    if ( $form->verifyForm() )
    {
    $sql = $form->getSQL_insertRow();
    if ( mysql_query($sql) )
    {
    echo "Computer info added

    ";
    showMainMenu();
    }
    else
    {
    echo "Can't do $sql" . ", " . mysql_error();
    $form->generateForm('form','process');
    }
    }
    else
    $form->generateForm('form','process');
    }
    else
    $form->generateForm('','process');
    }
    else if ( $_REQUEST['process'] == 'login' )
    {
    if ( isset($_REQUEST['username']) )
    {
    if ( $_REQUEST['username'] == $ADMIN_USERNAME && $_REQUEST['password'] == $ADMIN_PASSWORD )
    {
    $_SESSION['loggedIn']=true;
    showMainMenu();
    die();
    }
    else
    echo "Log-in failed";
    }

    echo "

    Username:


    Password:

    ";
    }
    else
    {
    showMainMenu();
    }

    ?>

    By : webhappy

    <?php
    /*
    CRITICAL NOTE!!!
    We MUST be guaranteed table structure does NOT change while we are using this script
    It can change after we have generated our PHP code, but not while we are between steps B and C, in particular
    */

    /*
    Generate form code
    A: DB name, table name
    B: List table columns -> checkbox, if to apply; possibly radio if different forms:
    if integer, only textbox; if varchar: textbox; blob/text: textbox or textarea
    C: Process choices->generate PHP:
    Produce function generateForm($source="","request","db")
    Produce function insertIntoDB; //grab data from _REQUEST
    */


    if ( !isset($db) || !isset($table) )
    {
    echo "<form action=$PHP_SELF>";
    echo "DB: <input name=db><br>
    Table: <input name=table><br>
    <input type=submit value=Go></form>";
    }
    else
    {
    if ( $ready )
    {
    // print_r($_POST);
    ob_start();
    echo '<?PHP
    class Form_'.$db.'_'.$table.' {
    var $TEXTAREA_ROWS=6;
    var $TEXTAREA_COLS=40;
    ';
    $fields = mysql_list_fields($db,$table);
    echo 'var $renderStyle=array(';
    $n=0;
    for ( $i=0; $i < mysql_num_fields($fields); $i++ )
    {
    if ( isset($_REQUEST["enable$i"]) )
    {
    echo ($n++==0?'':',').($n % 5 ==1?'
    ':'')."'".mysql_field_name($fields,$i).'\'=>'."'".$_POST["represent$i"]."'";
    }
    }
    echo ');
    ';//close the array()

    echo 'var $labels=array(';
    $n=0;
    for ( $i=0; $i < mysql_num_fields($fields); $i++ )
    {
    if ( isset($_REQUEST["enable$i"]) )
    {
    echo ($n++==0?'':',').($n % 3 ==1?'
    ':'')."'".mysql_field_name($fields,$i).'\'=>'."'".mysql_field_name($fields,$i)."'";
    }
    }
    echo ');
    ';
    /*
    END INITIALIZATION ARRAYS
    */

    echo '
    function generateForm ( $source="" )
    {
    $fields = array_keys($this->renderStyle);
    if ( $source == \'request\' || $source == \'input\' || $source ==\'form\' )
    {
    foreach ( $fields as $n=>$f)
    $$f=$_REQUEST[$f];
    }
    else if ( !empty($source) )
    {
    //$source should be a mySQL string
    $query = mysql_query($source);
    $data = mysql_fetch_array($query);

    //Begin conversion from DB row to our form variables
    foreach ( $fields as $n=>$f)
    $$f=$data[$f];
    }

    echo "<table><form action=$_SERVER[PHP_SELF] method=post>";
    echo "<input type=hidden name=submitted value=true>
    <input type=hidden name=process value=$_REQUEST[process]>";
    //Time to render the form itself, now that we have the variables;
    foreach ( $fields as $n=>$f )
    {
    echo "<tr><td>".$this->labels[$f]."</td><td>";
    switch($this->renderStyle[$f])
    {
    case \'textarea\':
    echo "<textarea name=$f rows=TEXTAREA_ROWS cols=TEXTAREA_COLS>".$$f."</textarea>";
    break;

    case \'input\':
    default:
    echo "<input type=text name=$f value=\"".$$f."\">";
    }
    echo "</td></tr>";
    }
    echo "<tr><td colspan=2><input type=submit value=\\"Submit\\"></td></tr></form></table>";
    }

    function verifyForm ()
    {
    foreach ( $this->renderStyle as $f=>$r)
    if ( empty($_REQUEST[$f]) )
    return false; //At least one empty element

    return true;
    }

    function getSQL_setClause ()
    {
    $c=0;
    $ret="";
    foreach ($this->renderStyle as $f=>$r)
    {
    if ( $c++ > 0 )
    $ret .= ",";
    $ret .= "$f=\'$_REQUEST[$f]\'";
    }
    return $ret;
    }

    function getSQL_updateRow ( $whereClause)
    {
    $sql = "update '.$table.' set " .$this->getSQL_setClause() . " where $whereClause";
    return $sql;
    }

    function getSQL_insertRow ()
    {
    $sql = "insert into '.$table.' set " . $this->getSQL_setClause();
    return $sql;
    }

    } //End Class
    ?>';
    $output=ob_get_contents();
    ob_end_clean();
    //echo "<hr>$output<hr>";
    highlight_string($output);

    }
    else
    {
    echo "<form action=$PHP_SELF method=post>";
    echo "<input type=hidden name=db value=$db><input type=hidden name=table value=$table>";
    echo "<input type=hidden name=ready value=true>";
    $fields = mysql_list_fields($db,$table);
    echo "<table>";
    for ( $i=0; $i < mysql_num_fields($fields); $i++ )
    {
    switch ( mysql_field_type($fields, $i) )
    {
    case 'int': case 'bigint': case 'mediumint':
    $choices = array("input"); break;
    case 'varchar':
    $choices = array("input"); break;
    case 'blob': case 'text':
    $choices = array("textarea", "input");break;
    default:
    $choices=array("input");
    }

    echo "<tr>";
    echo "<td><input type=checkbox name=enable$i value=true title=\"Enable this column\" checked></td>";
    echo "<td>".mysql_field_name($fields, $i) . "-<b>" . mysql_field_type($fields,$i) . "</b> " . mysql_field_len($fields,$i) ." (" . mysql_field_flags($fields,$i).")" . "</td>\n";

    foreach ( $choices as $n=>$k )
    {
    echo "<td><input type=radio name=represent$i value=$k " . ($n==0?'checked':'').">$k</td>";
    }
    echo "</tr>";
    }
    echo "</table>";
    echo "<input type=submit value=\"Generate PHP\"></form>";
    }
    }

    function ob_pre ( $buffer )
    {
    return "<pre>".$buffer."</pre>";
    }

    ?>
    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: The Integrated Project and Portfolio Management Platform.

    Hear how IBM Rational Project and Portfolio Management integrated solutions help teams put the right tools and processes in place to maximize the effectiveness and efficiency of project teams and ensure that the business vision is being executed correctly. Learn how to automate and integrate requirements prioritization, top-down project planning, communications and controls, and methodology deployment to keep your scope, costs, and schedules under control. Tackle with an end-to-end approach the management of scope and scope changes, usage of methodology to control and empower project teams, and optimization of resources to align activity costs with the overall project plan.
    FREE! Go There Now!


    NEW! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Addressing software-as-a-service challenges using Tivoli security and WebSphere solutions

    Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base.
    FREE! Go There Now!


    NEW! IBM Rational Systems Development e-Kit

    As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br />
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! Test terminal-based applications with Rational Functional Tester

    Regression testing -- in which code is thoroughly tested to ensure that changes have not produced unexpected results -- is an important part of any development process. But many testing environments neglect the terminal-based applications that still form the backbone of many industries. In this tutorial, you'll learn how the Rational Functional Tester Extension for Terminal-Based Applications works with other Rational Functional Tester to help test terminal-based applications quickly and easily.
    FREE! Go There Now!


    NEW! Trial download: IBM Informix Dynamic Server Express Edition V11.0

    Informix Dynamic Server (IDS) Express Edition offers outstanding online transaction processing (OLTP) database performance, while helping to simplify and automate many of the tasks associated with deploying databases for small business applications. IDS 11 further extends the ease of management and applications integration with the Admin API and Scheduler, high availability with Continuous Log Restore for backup server recovery in case of a primary server failure, and column level encryption to protect personal and company private data.
    FREE! Go There Now!


    NEW! Webcast: Calling All Testers! Find Application Vulnerabilities Early in the Development Process Where they are Easier to Fix and Less Risky to your Business

    In this webcast, IBM Rational will discuss the importance of Web application security and will share techniques and best practices to introduce application security testing into current QA processes including: understanding common security vulnerabilities and techniques to integrate security testing with defect tracking and remediation systems in an effort to safeguard sensitive online information.
    FREE! Go There Now!


    NEW! Whitepaper: Delivering SOA solutions: service lifecycle management

    The unprecedented scope of a service-oriented architecture (SOA) initiative brings to the forefront a number of management and governance issues that were sidestepped in the past. The key to a successful SOA implementation is managing and governing activities throughout the entire SOA delivery lifecycle by ensuring that services conform to the needs of all of the business’s stakeholders. Learn how service lifecycle management allows the business to ensure that the process by which services are defined, created, tested, deployed, optimized and retired is manageable, repeatable and auditable.
    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-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek