Today is: 11 January, 2012
Check todays hot topics

Dynamic Form Generation

This is a crappy dynamic form class I built. It's been stripped down to protect the innocent. It's actually kinda useful if you have to generate a lot of forms. This does not include a post handler, control scripts or templates. If you scroll to the bottom you'll see a simple use case.

Think of this as a 'survey' generator. It's sibling class stores answers. It's got a whole lot of logic flaws and is presented as is. For example, what am I to do with answers to a form thats since been deactivated? Not as big of a problem as what to do with answers to a form that has since been deleted. Or answers to invalidated questions? I dunno. I don't really care. If you find it useful you'll clearly be modifying it to suit your needs. Lemme know if you've got an implementation of it, I always like to see my crap in motion.

This was written as a protest to PEAR modules and/or the Zend quickform framework. I don't really feel like being certified to manage forms. This is considered infinitely more awesome because it was written by me.

Schema

CREATE TABLE d_questions (
        id int not null auto_increment,
        question varchar(255) not null,
        form_id int not null,
        active varchar(1) not null,
        has_comment varchar(1) not null,
        block_id int not null,
        primary key(id)
);
 
CREATE TABLE d_forms (
        form_id int not null auto_increment,
        form_name varchar(30) not null,
        active varchar(1) not null,
        primary key(form_id)
);
 
CREATE TABLE d_blocks (
        block_id int not null auto_increment,
        block_name varchar(100) not null,
        form_id int not null,
        active varchar(1) not null,
        primary key(block_id)
);
 
CREATE TABLE d_form_blocks (
        form_id int not null,
        block_id int not null
);

Class

class form {
        // require("../conf/config.php"); // alternatively include these vars from somewhere else.
 
        var $dbHost = "";
        var $dbUser = "";
        var $dbPass = "";
 
        var $dbData = "";
        var $dbTabl = "";
 
        var $dbConn;
 
        // Object Constructor
        function form($dbConn = "") {
                $this->dbConn = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die(mysql_error());
                if($this->dbConn) { 
                        mysql_select_db($this->dbData) or die(mysql_error());
                }
        }
 
        function test() {
                $res = $this->query("SELECT * FROM sometable");
                if(is_array($res)) {
                        echo "<pre>\n";
                        print_r($res);
                        echo "</pre>\n";
                } else { 
                        die("Database Error. Ref ".__LINE__);
                }
        }
 
        private function query($sql) {
                $res = mysql_db_query($this->dbData, $sql, $this->dbConn);
                return $res ? $this->structure($res) : mysql_error();
        }
 
        private function insert($sql) {
                $res = mysql_db_query($this->dbData, $sql, $this->dbConn);
                return $res ? $res : mysql_error();
        }
 
        private function structure($res) {
                $count = 0;
                $database['FIELDS'] = array();
                $database['ROWS'] = mysql_num_rows($res);
                while($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
                        for ($i=0 ; $i < mysql_num_fields($res) ; $i++) {
                                $meta = mysql_fetch_field($res, $i);
                                $database['RESULTS'][$count][$meta->name] = $row[$meta->name];
                                if(!in_array($meta->name, $database['FIELDS'])) {
                                        array_push($database['FIELDS'], $meta->name);
                                }
                        }
                        $count++;
                }
                return $database;
        }
 
        // Get form
        public function get_form($formID) {
                $form = array();
                $this->validate($formID, __LINE__, __FUNCTION__);
 
                if(!$this->check_form($formID)) {
                        $this->error("Form does not exist", __LINE__, __FUNCTION__);
                }
 
                // ASSEMBLE FORM ARRAY AND POPULATE THE FORM KEY WITH INFO
                $res = $this->query("SELECT form_id, form_name from d_forms where form_id=".$formID);
                $form['FORM']['name'] = $res['RESULTS'][0]['form_name'];
                $form['FORM']['id'] = $res['RESULTS'][0]['form_id'];
 
                // POPULATE BLOCKS KEY WITH BLOCK INFO 
                $blocks = $this->get_blocks($formID);
                foreach($blocks['RESULTS'] as $thisone) {
                        $form['BLOCKS'][$thisone['block_id']] = $thisone;
                }
 
                // POPULATE BLOCKS WITH QUESTIONSa
                foreach($form['BLOCKS'] as $blockID) {
                        $res = $this->get_questions((int) $blockID['block_id']);
                        for($i = 0; $i <= ($res['ROWS'] - 1); $i++) {
                                $form['BLOCKS'][$blockID['block_id']]['QUESTIONS'][$i] = $res['RESULTS'][$i];
                        }
                }
                return $form;
        }
 
        public function get_forms() {
                $res = $this->query("SELECT distinct(form_id), form_name, active from d_forms");
                return $res;
        }
 
        private function validate($id, $line="", $function = "") {
                if(is_int($id)) {
                        return;
                } else {
                        $this->error("Please supply a valid form or block ID on $line $function");
                }
        }
 
        private function make_safe($data) {
                $data = htmlentities($data, ENT_QUOTES);
                $data = mysql_real_escape_string($data);
                return $data;
        }
 
        private function check_form($formID) {
                $this->validate($formID);
 
                $res = $this->query("SELECT * FROM d_forms WHERE form_id = ".$formID);
 
                return ($res['ROWS'] > 0) ? TRUE : FALSE;
        }
 
        public function add_block($formID, $name) {
                $this->validate($formID, __LINE__);
                $name = $this->make_safe($name);
 
                if(!$this->check_form($formID)) {
                        $this->error("Form does not exist", __LINE__);
                }
 
                $res = $this->insert("INSERT INTO d_blocks ".
                                "(block_name, form_id, active) ".
                                "VALUES".
                                "('".$name."',".$formID.",'y')");
 
                if(mysql_affected_rows() < 0) {
                        $this->error("Block INSERT failed. ($res)", __LINE__);
                }
 
                $blockID = mysql_insert_id();
                unset($res);
                $res = $this->insert("INSERT INTO d_form_blocks ".
                                "(form_id, block_id) ".
                                "VALUES".
                                "(".$formID.",".$blockID.")");
 
                if(mysql_affected_rows() < 0) {
                        $this->error("Block ID to Form ID association failed", __LINE__);
                }
                return $blockID;
        }
 
        public function add_form($name) {
                $name = $this->make_safe($name);
 
                $res = $this->insert("INSERT INTO d_forms ".
                                "(form_name, active) ".
                                "VALUES('".$name."','y')");
 
                if(mysql_affected_rows() < 0) {
                        $this->error("Form INSERT failed. ($res)", __LINE__);
                }
                $formID = mysql_insert_id();
                return ($formID > 0) ? $formID : -1;
        }
 
        public function del_form($formID) {
                $this->validate($formID);
                $blockIDs = array();
                $res = $this->query("SELECT block_id FROM d_form_blocks WHERE form_id = ".$formID);
        }
 
        public function add_question($formID, $blockID, $question, $has_comment = "n") {
                $this->validate($formID, __LINE__); 
                $this->validate($blockID, __LINE__);
                $question = $this->make_safe($question);
 
                $res = $this->insert("INSERT INTO d_questions ".
                                "(question, form_id, active, block_id, has_comment) ".
                                "VALUES('".$question."',".$formID.",'y',".$blockID.",'".$has_comment."')");
 
                if(mysql_affected_rows() < 0) {
                        $this->error("Question INSERT failed. ($res)", __LINE__);
                }
                $questionID = mysql_insert_id();
                return $questionID;
        }
 
        public function get_questions($blockID) {
                $this->validate($blockID, __LINE__);
 
                $res = $this->query("SELECT id, question, has_comment, block_id ".
                                        "FROM d_questions ".
                                        "WHERE block_id = ".$blockID );
                return $res;
        }
 
        public function get_blocks($formID) {
                $this->validate($formID, __LINE__);
                $blocks = $this->query("SELECT b.block_id, b.block_name from ".
                                        "d_blocks b ".
                                        "WHERE ".
                                        "active = 'y' AND ".
                                        "form_id = ".$formID);
                if(is_array($blocks)) {
                        return $blocks;
                } else { 
                        $this->error($blocks, __LINE__);
                }
        }
 
        private function error($string, $line = "", $function = "") {
                die("FATAL: $string, $line $function");
        }
}
?>

Test it!

<?php
 
require("includes/form.class.php");
 
$form = new form();
 
echo "Return a list of active forms.<br>";
$fs = $form->get_forms();
echo "<pre>"; print_r($fs); echo "</pre>";
 
echo "Return a model of a specific form. In this case form ID 22<br>";
$f = $form->get_form(22);
 
echo "<pre>"; print_r($f); echo "</pre>";
 
?>