Your script looks up each name in a hash before inserting it into your database and saving it into the hash. That works as long as your script runs, but when it stops your hash no longer exists. The database persists when the script isn't running, so you need to attempt to select the name from your database before inserting it. For example:
my ($name, $phone) = ('Jane Doe', '123 4567');
# execute SELECT query
my $sth = $dbh->prepare("SELECT name FROM Phonebook WHERE name = ?");
$sth->execute($name);
#Fetch result into hash reference
my $ref = $sth->fetchrow_hashref();
if (defined $ref->{'name'}){
die "A record for $name already exists in the phonebook.\n";
}
else{
#Prepare insert statement
$sth = $dbh->prepare('INSERT INTO Phonebook (name, Phone) VALUES (?, ?)')
or die "Couldn't prepare statement: " . $dbh->errstr;
$sth->execute($name, $phone);
print "$name $phone successfully added.\n";
} d5e5
Practically a Posting Shark
810 posts since Sep 2009
Reputation Points: 159
Solved Threads: 159