#!/usr/bin/perl

use DBI;

package Sql;

sub new(%)
{
  my $Invocation = shift(@_);
  my %Params = @_;
  my $Class = ref($Invocation) || $Invocation;
  my $this = {
               _dbh => undef,
	       _sth => undef,
               _DBHOST => undef,
               _DBNAME => undef,
               _DBUSER => undef,
               _DBPASS => undef
	     };
  
  # bless you ;)  
  bless($this, $Class);
  
  $this->{_DBHOST} = $Params{'dbhost'} ? $Params{'dbhost'} : 'localhost';
  $this->{_DBNAME} = $Params{'dbname'} ? $Params{'dbname'} : undef;
  $this->{_DBUSER} = $Params{'dbuser'} ? $Params{'dbuser'} : undef;
  $this->{_DBPASS} = $Params{'dbpass'} ? $Params{'dbpass'} : undef;
  $this->open();
  
  return($this);  
}

sub open()
{
  my $this = shift(@_);
  $this->{_dbh} = DBI->connect("DBI:mysql:database=$this->{_DBNAME};host=$this->{_DBHOST}","$this->{_DBUSER}","$this->{_DBPASS}", {PrintError=>1});
  unless($this->{_dbh})
  {
    $this->error($DBI::errstr);
    exit 1000;
  }
}

sub close()
{
  my $this = shift(@_);
  ($this->{_dbh})->disconnect();
}

sub executeNonQuery($)
{
  my $this = shift(@_);
  my $Statement = shift(@_);
  return($this->{_dbh}->do($Statement));
}

sub execute($)
{
  my $this = shift(@_);
  my $Statement = shift(@_);
  $this->{_sth} = $this->{_dbh}->prepare($Statement);
  $this->{_sth}->execute();
}

sub executeScalar($)
{
  my $this = shift(@_);
  my $Statement = shift(@_);
  my $retval;
  $this->{_sth} = $this->{_dbh}->prepare($Statement);
  $this->{_sth}->execute();
  if($this->{_sth})
  {
    $res = $this->{_sth}->fetchrow_arrayref();
    if($res)
    {
      $retval = $res->[0];
    }
    $this->{_sth}->finish();
    undef($this->{_sth});
  }
  return($retval);
}

sub read()
{
  my $this = shift(@_);
  my $hashref = $this->{_sth}->fetchrow_hashref();
  return($hashref);
}

sub error($)
{
  my $this = shift(@_);
  my $ErrMsg = $_[0];
  print "<font color=\"red\" size=\"3\"><u>database error:</u><br/><b>$ErrMsg</b></font>";  
}

sub quote($)
{
  my $this = shift(@_);
  my $String = shift(@_);
  $String =~ s/(;|'|\\|\n)/\\$1/g;
  return($String);
}

sub numeric($)
{
  my $this = shift(@_);
  my $String = shift(@_);
  $String =~ s/[^-\.0-9]//g;
  return($String);
}

1;

