But first, let's correct your code. In your code, when the fetch loop exits you will be left with an empty @row array, so your test will always be false. You should instead do something like this:
I think you also have a problem with the actual SELECT statement, where I would drop the quotes around Names.while(@row = $sth->fetchrow_array) { ++$duplicate; }
Now there is a more fundamental problem with this approach: What happens if someone inserts the same name between the time you run your check and the time you try to insert it? Unless you are certain that your script will be running all by itself you should let the database check for duplicates for you.
This involves creating a unique index (or a unique constraint) on the Names column, attempting the insert and checking for a duplicate key error. Using RaiseError and eval makes this quite easy:
Good luck!my $dbh = DBI->connect($dsn, $usr, $pwd, {RaiseError => 1}); my $sth = $dbh->prepare("insert into Customers(Names, ...) values(?, . +..)"); eval { $sth->execute($new_name, ...); }; if($@) { # Got an error! # The insert failed - probably due to the duplicate key constraint # You can check the $@ variable which holds the error # string that caused the insert to fail to see what # error happened. # Handle this the same way that you would handle the # case where your checkDuplicateName() returns true }
Michael
In reply to Re: Database stuff
by mpeppler
in thread Database stuff
by Raziel
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |