#!/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");

@names = $query->param;
$selstr = '';
$setstr = '';
while ($name = shift @names) {
  if ($name =~ m/^field_(.*)/) {
    if ($selstr ne '') {
      $selstr .= ' and ';
    }
    $selstr .= "$1='".$query->param($name)."'";
  }
  if ($name =~ m/^update_(.*)/) {
    if ($setstr ne '') {
      $setstr .= ', ';
    }
    $setstr .= "$1='".$query->param($name)."'";
  }
}
$cursor=$dbh->prepare("update $table set $setstr where $selstr") || 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;
}
      
