#!/usr/bin/perl
use crsTools4;
connect2db;
# Test query using $sth
run_sql("SELECT * FROM person WHERE firstname = 'Joe'");
while ((@f) = $sth->fetchrow())
{ print "@f\n" }
# Test query using $sth2 (though I could just reuse $sth in this case)
run_sql("SELECT * FROM person WHERE firstname = ? AND surname = ?",2,'Joe','Bloggs');
# while ((@f) = $sth2->fetchrow())
while ((@f) = $sth->fetchrow())
{ print "@f\n" }
####
package crsTools4;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(connect2db run_sql); # Symbols to be exported by default
our @EXPORT_OK = qw($dbh $sth);
sub connect2db
{
require DBI;
our $dbh = DBI->connect("DBI:mysql:database=crs;host=127.0.0.1", 'crs_user', 'mypw') or die('Could not connect!');
}
# Execute an SQL command (arg 1), with an optional specified handle #
# (arg 2), and optional bind variables (args 3...).
sub run_sql
{
my ($sql, $n) = (shift @_, shift @_);
print "sql=\"$sql\", sth$n, bind=\"" . join(',',@_) . "\"\n";
# $$sth = $dbh->prepare($sql);
# $$sth->execute(@_) or die "Could not execute: $DBI::errstr\n";
# To make things simple while debugging, let's just hard-code $sth
$sth = $dbh->prepare($sql);
$sth->execute or die "Could not execute: $DBI::errstr\n";
}
1; # Required for all packages, to return a true value
####
sql="SELECT * FROM person WHERE firstname = 'Joe'", sth, bind=""
Can't call method "fetchrow" on an undefined value at ./test4.pl line 9.