#! /usr/bin/perl

# show_member - quick display of Historical League member entries

# Usage: show_member [ member_number | last_name ]

# last_name can be a SQL pattern

use DBI;
use strict;

@ARGV or die "Usage: show_member [ member_number | last_name ]\n";

# host, user, password are assumed to come from ~/.my.cnf

my ($dsn, $dbh);
my (%attr) = ( RaiseError => 1 );

$dsn = "dbi:mysql:samp_db;mysql_read_default_file=$ENV{HOME}/.my.cnf";
$dbh = DBI->connect ($dsn, undef, undef, \%attr);

# MAIN-BODY
my ($count) = 0;	# number of entries printed so far
my (@label) = ();	# column label array
my ($label_wid) = 0;

while (@ARGV)		# run query for each argument on command line
{
my ($arg) = shift (@ARGV);
my ($sth, $clause, $address);

	# default is last name search; do id search if argument is numeric
	$clause = "last_name LIKE " . $dbh->quote ($arg);
	$clause = "member_id = " . $dbh->quote ($arg) if $arg =~ /^\d/;

	# issue query
	$sth = $dbh->prepare (qq{
		SELECT * FROM member
		WHERE $clause
		ORDER BY last_name, first_name
	});
	$sth->execute ();

	# get column names to use for labels and
	# determine max column name width for formatting
	# (only do this the first time through the loop, though)
	if ($label_wid == 0)
	{
		@label = @{$sth->{NAME}};
		foreach my $label (@label)
		{
			$label_wid = length ($label) if $label_wid < length ($label);
		}
	}

	# read and print query results, then clean up
	while (my @ary = $sth->fetchrow_array ())
	{
		# print newline before 2nd and subsequent entries
		print "\n" if ++$count > 1;
		foreach (my $i = 0; $i < $sth->{NUM_OF_FIELDS}; $i++)
		{
			# print label, and value if there is one
			printf "%-*s", $label_wid+1, $label[$i] . ":";
			print " " . $ary[$i] if $ary[$i];
			print "\n";
		}
	}
	$sth->finish ();
}
# MAIN-BODY

$dbh->disconnect ();
exit (0);
