#!/usr/bin/perl

use CGI;
use DBI;

$query=new CGI;
$address  = $query->param('address')  || 'dewey';
$database = $query->param('database') || 'mysql';
$username = $query->param('username') || 'bastille';
$password = $query->param('password') || '';
$table    = $query->param('table')    || 'user';
$select   = $query->param('select')   || 'select * from '.$table;
if ($password eq '') { $pwstring = ''; } else { $pwstring = '-p=$password' };

#load the driver for mysql
$drh=DBI->install_driver('mysql') || cgidie("Could not load mysql driver\n");

$dbh=$drh->connect("$database:$address","$username","$password") || cgidie("Failed to connect to mysql server\n");

$cursor=$dbh->prepare("describe $table") || cgidie("Describe failed: describe $t
able");
$cursor->execute;
@fields = ();
@fielddefaults = ();
while (@fielddesc = $cursor->fetchrow) {
  push @fields, $fielddesc[0];
  push @fielddefaults, $fielddesc[4];
}

$insertstr = '';
while ($field = shift @fields) {
  $default = shift @fielddefaults;
  $txt = $query->param("field_$field") || $default;
  if ($insertstr ne '') {
    $insertstr .= ', ';
  }
  $insertstr .= "'$txt'";
}

$cursor=$dbh->prepare("insert into $table values ($insertstr)") || cgidie("Prepare failed.");
$cursor->execute || cgidie("Execute Failed!".$cursor->errstr);

print "Content-type: text/html\nLocation: use_table.pl?address=$address&database=$database&username=$username&password=$password&table=$table&select=$select\n\n";

sub cgidie {
  ($die_str) = @_;
print <<EOF
Content-Type: text/html

CGI_Error:<p><pre>
$die_str
</pre>
</body>
</HTML>
EOF
;
  die $dir_str;
}
