<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Database;

use strict;
use DBI;
use CGI::Carp;

sub new()
{
	my $pkg = shift;
	my $obj = { 
		'queries'		=&gt; 0,
		'database'	=&gt; '',
		'user'			=&gt; '',
		'password'	=&gt; '',
		'host'			=&gt; '',
		'dbh'				=&gt; undef,
		'error'     =&gt; undef
	};
	bless $obj, $pkg;
	return $obj;
}

sub init()
{
	my $this = shift;
	my ($user, $password, $database, $host, $error) = @_;
	$host = 'localhost' unless $host;
	if ($error) {
		$this-&gt;{'error'} = $error;
	} else {
		$this-&gt;{'error'} = \&amp;error;
	}
	$this-&gt;{'dbh'} = DBI-&gt;connect("DBI:mysql:$database:$host:3306", $user, $password) or $this-&gt;{'error'}-&gt;(Carp::longmess(DBI::errstr), 1);
}

sub close()
{
	my $this = shift;
	$this-&gt;{'dbh'}-&gt;disconnect();
}

sub query()
{
	my ($this, $query) = @_;
	my $sth = $this-&gt;{'dbh'}-&gt;prepare($query);
	$this-&gt;{'query'} = $query;
	$sth-&gt;execute() or $this-&gt;{'error'}-&gt;(Carp::longmess("Couldn't execute statement: " . $sth-&gt;errstr . " in query " . $query), 1);
	$this-&gt;{'queries'}++;
	return $sth;
}

sub prepare()
{
	my ($this, $query) = @_;
	$this-&gt;{'sth'} = $this-&gt;{'dbh'}-&gt;prepare($query);
	$this-&gt;{'query'} = $query;
	return $this-&gt;{'sth'};
}

sub execute()
{
	my ($this, @params) = @_;
	return unless $this-&gt;{'sth'};
	$this-&gt;{'sth'}-&gt;execute(@params) or $this-&gt;{'error'}-&gt;(Carp::longmess("Couldn't execute statement: " . $this-&gt;{'sth'}-&gt;errstr . " in query " . $this-&gt;{'query'}), 1);
	return $this-&gt;{'sth'};
}

sub start_transaction()
{
	my $this = shift;

	# Abort if we're already in a transaction
	if ($this-&gt;{'transaction'}) {
		return;
	}

	my $sth = $this-&gt;{'dbh'}-&gt;prepare('BEGIN');
	$sth-&gt;execute();
	$this-&gt;{'transaction'} = 1;
}

sub commit_transaction()
{
	my $this = shift;

	# Abort if we're not in a transaction
	unless ($this-&gt;{'transaction'}) {
		return;
	}

	my $sth = $this-&gt;{'dbh'}-&gt;prepare('COMMIT');
	$sth-&gt;execute();
	$this-&gt;{'transaction'} = 0;
}

sub rollback_transaction()
{
	my $this = shift;

	# Abort if we're not in a transaction
	unless ($this-&gt;{'transaction'}) {
		return;
	}

	my $sth = $this-&gt;{'dbh'}-&gt;prepare('ROLLBACK');
	$sth-&gt;execute();
	$this-&gt;{'transaction'} = 0;
}	

sub num_queries()
{
	my $this = shift;
	return $this-&gt;{'queries'};
}

sub insert_id()
{
	my $this = shift;
	return $this-&gt;{'dbh'}-&gt;{'mysql_insertid'};
}

sub error()
{
	my $message = shift;
	die $message;
}

1;
</pre></body></html>