#!/usr/local/bin/perl -w
# Free query
use DBI;
use CGI;


$database = '***';
$hostname = '***';
$user = '***';
$password = '***';


$query = new CGI;
print $query->header;
$TITLE="Query Form";

$path_info = $query->path_info;

# If no path information is provided, then we create 
# a side-by-side frame set
if (!$path_info) {
    &print_frameset;
    exit 0;
}


#Start HTML page

&print_html_header;
&print_query if $path_info=~/query/;
&print_response if $path_info=~/response/;
&print_end;
exit;

#----------------------------------------
# Subroutines
#-----------------------------------------

sub print_html_header {
    print $query->start_html($TITLE);
}
#-----------------------------------------
sub print_end {
       print $query->end_html;
}
#-----------------------------------------
sub print_frameset {
    $script_name = $query->script_name;
    print <<EOF;
<html><head><title>$TITLE</title></head>
<frameset cols="50,50">
<frame src="$script_name/query" name="query">
<frame src="$script_name/response" name="response">
</frameset>
EOF
    ;
    exit 0;
}
#------------------------------------------

sub print_query{
    $script_name = $query->script_name;
    print "<H1>Query</H1>\n";
    print    $query->startform(-action=>"$script_name/response",-TARGET=>"response");

       
    print "<P> SQL QUERY: <BR> (command) ",
    $query->textfield(-name=>'command', 
			-default=>'show tables',
			-size=>50,
			-maxlength=>200);


    print "<BR><BR>",$query->submit (' Submit query ');
    print $query->endform;

print qq{<P><A href="http://barley.itc.nl/VRML/START7.html" TARGET= "vrml" >back</A></P>};

print "<P><BR>permitted commands: <BR><BR>CREATE TABLE, SELECT, JOIN, INSERT, LOAD DATA INFILE, SHOW, EXPLAIN<P>";

print qq{<P><B><I><FONT COLOR=red><FONT SIZE=0>check the syntax with the documentation <A HREF="http://barley.itc.nl/manual_leter.pdf">PDF</A> or <A HREF="http://www.mysql.com/doc.html">on-line</A> version</FONT></FONT></I></B></P>};

}
#--------------------------------------------
sub print_response {
    print "<H1>Result</H1>\n";
    unless ($query->param) {
	print "<b>No query submitted yet.</b>";
	return;
    }


#Query database------------------------------------------

$command = $query->param('command');

print "<P><B><FONT COLOR=red>$command</FONT></B></P>";


$dbh = DBI->connect ("DBI:mysql:$database:$hostname", $user,$password);

if ($command eq '') {
   print "<P><B><FONT COLOR=red>No command submitted yet</FONT></B></P>";
   $dbh->disconnect; 
   return;  
}

$sth = $dbh->prepare("$command");
$sth->execute;

$num=0;

while (@field = $sth->fetchrow) {   
  $all[$num]=[@field];
  $num_rec=@field;

  for ($i=0;$i<$num_rec; $i++) {
    
     print "$all[$num]->[$i]  ";
  }
  print "<BR>";
  $num++;
}

$sth->finish;

$dbh->disconnect; 

}


