in reply to OT - MySQL report generation
Here is some code we use at PerlMonks. I think vroom wrote the first version (but I doubt he'd mind me releasing it). I patched it some after that and I've removed some of the PM-specific bits (such as the template that it is embedded in, which dictated some of the structure of it).
You'll have to paste in your own DB connect method and this code doesn't deal with DB errors (the templating system already does that, if rather verbosely, so we haven't bothered to put such in here).
use CGI; my $q = CGI->new(); print $q->header(); my $db = Your::Module::GetYourDataBaseHandle(); my $html = ''; my $execstr = $q->param("sqlquery"); $html .= $q->start_multipart_form( "POST", $ENV{script_name}) . "\n" . $q->hidden("displaytype") . "\n" . $q->hidden("node_id", getId($NODE)) . "\n" . "SQL Query:<br />\n" . $q->textarea( "sqlquery", $execstr, 8, 60 ) . "<br />\n" . $q->submit('execsql', 'Execute') . "\n" . $q->end_form(); print $html; $html = ''; if( $execstr ) { my $cursor = $db->prepare($execstr); my $count = eval { $cursor->execute() }; if( ! $count ) { $html= "Execute failed: $DBI::errstr\n"; } elsif( ! $cursor->{NUM_OF_FIELDS} ) { # not a select statement $html= "$count rows affected.\n"; } else { my $ROW; while( $ROW = $cursor->fetchrow_hashref() ) { if( $html eq "" ) { $html = "$count rows:\n<table border=1>\n"; $html .= " <tr>\n"; foreach ( @{$cursor->{NAME}} ) { if( ! defined $_ ) { $_= ""; } elsif( "" eq $_ ) { $_= " "; } else { $_= $q->escapeHTML($_); } $html .= qq[ <td align="center" bgcolor="#CC99CC">] . qq[<font color="#000000">$_</font></td>\n]; } $html .= " </tr>\n"; } $html .= " <tr>\n"; my( $k, $v ); foreach ( @{$cursor->{NAME}} ) { #(keys %$ROW) $k = $_; $v = $$ROW{$_}; if( ! defined $v ) { $v= ""; } elsif( "" eq $v ) { $v= " "; } else { $v= $q->escapeHTML($v); $v =~ s# # #g; $v =~ s#\n#<br />\n#g; } $html .= " <td>$v</td>\n"; } $html .= " </tr>\n"; } $cursor->finish(); if( $html eq "" ) { $html .= "Zero rows returned.\n"; } else { $html .= "</table>\n" } } } print $html;
I've tested the original code quite a bit but I've not even tried to compile this reinterpretation of it.
|
|---|