There are a number of issues with the way you propose to do this check.

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:

while(@row = $sth->fetchrow_array) { ++$duplicate; }
I think you also have a problem with the actual SELECT statement, where I would drop the quotes around Names.

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:

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 }
Good luck!

Michael


In reply to Re: Database stuff by mpeppler
in thread Database stuff by Raziel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.