## Wednesday, August 20, 2008

### Handy Perl Functions: Automatically create a form from a database table

Back after a much needed vacation with another perl code snippet. This one creates a simple form using information pulled from the structure of a database table. The form it creates is not meant to be the end product - rather it gets a lot of the "grunt work" done, and you can then edit the resulting form to change fields to drop-downs, remove fields that shouldn't be edited, etc. It will also try to guess at a decent label for each field, based on the table name.

This script uses the same get_fields() function that outlined in my previous post.

As always, I'm sure this isn't the "perfect" code, and of course it can be improved - but it does work, and may perhaps be a useful starting block for someone else...

Usage - pretty simple - run the script and give it a database table name to use. It'll spit the html back out, which you can save in a text file or whatever.

#!/usr/bin/perl# creates a basic form from the database table specifieduse DBI;# database connection detailsmy $dsn = "DBI:mysql:database=[YOUR DATABASE];host=localhost";$dbh = DBI->connect($dsn,"root","");my$qry = "";my $html = "";my$table = $ARGV[0];if (not$table) {       print "Please specify a table...\n";       exit;       }my @fields = &get_fields($table);$html = "<form action="\[YOUR PROCESSING SCRIPT]\" method="\post\"><table border="0" cellpadding="4" cellspacing="0">\n";foreach $_ (@fields) { my$ucfield = uc $_; my$name = ucfirst $_;$name =~ s/_/ /g;       html .= " <tbody><tr valign="\top\"> <td align="\right\"><b>name</b></td>               <td><input name="\$_\" value="\-$ucfield-\" type="\text\"></td>       </tr>\n";       }html .= "<tr> <td colspan="2" align="\center\"><input value="\Submit\" type="\submit\"></td></tr></tbody></table></form>\n";printhtml;