954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

pearl database related question

when I'm running the code everything works fine, it doesnt allow you enter the same name twice but if I shut it down and then start the code again it will let me add the same name again without throwing the error message. does anyone know I could change my code to stop this from happening?
http://pastebin.com/aykN62NX

jrp370
Newbie Poster
19 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

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
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You