my $dbh = do_dbi_connect( $db_type, $db_name, $db_username, $db_password, @_ ); my $sql =<fetchrow_array() ) { # blah } $sth->finish ##### STANDARD DATABASE FUNCTIONS ##### # do_dbi_connect( DB_TYPE, DB_NAME, DB_USERNAME, DB_PASSWORD, @OPTIONS ) # connect to the specified DB_TYPE and DB_NAME using the DB_USERNAME and # DB_PASSOWRD as well as passing any other @OPTIONS # returns the DBH sub do_dbi_connect { my ( $db_type, $db_name, $db_username, $db_password ) = ( shift, shift, shift, shift ); my $dbh = DBI->connect("dbi:$db_type:$db_name", $db_username, $db_password ) or die_nice( $DBI::errstr ); return $dbh; } # do_sql( DBH, SQL, BIND_VAL1.....BIND_VALx ) # prepares, executes and closes sth in one call # typical use for create tables, update tables sub do_sql { my $dbh = shift; my $sql = shift; my $sth = get_sth( $dbh, $sql ); $sth->execute(@_) or die_nice( "Could not execute SQL statement\n\n$sql\n" . $sth->errstr() ); $sth->finish; } # do_sql_sth( DBH, SQL, BIND_VAL1.....BIND_VALx ) # as for do_sql but returns the STH # obviously does not call finish on the STH (so you have to remember) # typical use for fetchrow_blah sub do_sql_sth { my $dbh = shift; my $sql = shift; my $sth = get_sth( $dbh, $sql ); $sth->execute(@_) or die_nice( "Could not execute SQL statement\n\n$sql\n" . $sth->errstr() ); return $sth; } # get_sth( DBH, SQL ) # returns a (cached) STH for the supplied DBH and SQL sub get_sth { my ( $dbh, $sql ) = @_; my $sth = $dbh->prepare_cached($sql) or die_nice( "Could not prepare SQL statement\n\n$sql\n" . $dbh->errstr() ); return $sth; } # die nice( ERROR ) # dies with ERROR after printing a valid header and error message to browser # you may choose to modify this to produce a BS message to the user like # 'the server can not respond to your request at this time due to routine maintenance' # or some such rubbish. just make sure you get to see the ERROR! sub die_nice { print "Content-type: text/html\n\n$_[0]"; die $_[0] }