#!/usr/bin/perl

use DBI;
use CGI;

$param=new CGI;
$tabulka = $param ->param('table');
$spesl = $param ->param('spesl');
$order = $param ->param('order');

print "Content-type:text/html\n\n";
&init;
print "<body bgcolor='#ffffff'><b>Mysql editor</b>  v0.2<br>";
print "Select a table : <br>";
foreach $r (@TABL)
{
 print qq( <a href="view.cgi?table=$r"><b>$r</b></a> |);
}

if ($tabulka)
{
print qq(\n<br><hr>Selected table : <b>$tabulka</b><br>
<a href="insert.cgi?table=$tabulka">New record</a>
);

if(!$COLS{$tabulka}){$COLS{$tabulka}="*";};
$dbh = DBI->connect("$INIT","$LOGIN","$PASS");


if ($spesl)
{
 if ($order){$spesl=$spesl . $order};
 $sth=$dbh->prepare($spesl);
 $sth->execute;
 @sloupce = @{$sth->{NAME}};
 $sqlv=$spesl;
}else
{
 $sth=$dbh->prepare("select $COLS{$tabulka} from $tabulka $order");
 $sth->execute;
 @sloupce = @{$sth->{NAME}};
 $t="@sloupce";
 $t=~tr/ /,/;
 $sqlv="select $t from $tabulka$order";
}


print qq(<pre>\(<font size="-2">expert mode</font>\)<form><input type="hidden" name="table" value="$tabulka"><input type="text" size="70" name="spesl" value="$sqlv"><input type="Submit" name="ok" value="ok"></form></pre>);



print qq(<br>
<table border="1" width="100%">
<tr>
);

$spesl=~s/\s*order\s*by\s*.*//i;
foreach $ra(@sloupce)
{
 $spesl=~tr/ /+/;
 $spesl=~s/,/%2C/g;
 print qq(<td bgcolor='#eeeeee'>&nbsp;<b><a href="view.cgi?table=$tabulka&spesl=$spesl&order=+order+by+$ra">$ra</a></b></td>\n);
}


print "<td bgcolor='#eeeeee' width='20'>&nbsp;</td><td bgcolor='#eeeeee' width='20'>dell</td></tr>\n";
while (@rr=$sth->fetchrow_array)
{
	print "<tr>";
	foreach $ra(@rr)
	{
	 print "<td>&nbsp;$ra</td>";
	}
	print qq(<td valign="bottom"><a href="edit.cgi?table=$tabulka&radka=@rr[0]&id=$sloupce[0]">edit</a></td><td valign="bottom">
	&nbsp; <a href="#" onClick="if \(confirm\('Delete ?'\)\){this.href='dell.cgi?table=$tabulka&radka=@rr[0]&id=$sloupce[0]'}">x</a>
	</td></tr>\n);
}


print "</table>
</body>
";


$dbh->disconnect;
}

# -------------------------------------------------
sub init
{
 open(F,"dat.conf");
 @o =<F>;
 close(F);
 %COLS=();
 foreach $radek (@o)
 {
  next if $radek=~/^#/; next unless $radek=~/\S/;
  if ($radek=~/^init/i)   {($INIT)=($radek=~/^init\s*=\s*(\S*)/i);};
  if ($radek=~/^login/i)   {($LOGIN)=($radek=~/^login\s*=\s*(\S*)/i);};
  if ($radek=~/^pass/i)   {($PASS)=($radek=~/^pass\s*=\s*(\S*)/i);};
  if ($radek=~/^tables/i) {($tmp)=($radek=~/^tables\s*=\s*(.*)/i);$tmp=~s/\s*//g;@TABL=split(",",$tmp);};
  if ($radek=~/^view/i) {($tmp1,$tmp2)=($radek=~/^view\s*(.*?)\s*=\s*(.*)/i);$tmp2=~s/\s*//g;$tmp2=~s/,/,/g;$COLS{"$tmp1"}="$tmp2";};
 }
 if(!$INIT) {&err("100","No init string");exit(0);}
}

sub err
{
 print "<br> Error :<b>$_[0]</b> : $_[1]\n";
}