SPUG: Using a Duplicate Value Error Message

BenRifkah Bergsten-Buret benb at speakeasy.net
Tue Mar 20 09:56:09 PDT 2007

Welcome Will,

Will Kidwell wrote:
> I've got RaiseError working, and it might be possible to use it 
> somehow to set a variable equal to 1 for "Try Again" or "0" for 
> "Success", but if thats the answer I'm still not sure of how to write 
> it out.
Just some background to start: Is the handles.users column restricted to 
unique values using some kind of duplicate key constraint?  If so it 
seems like you won't be able to insert duplicate entries am I right?  If 
that's the case then you're most of the way there.  You mentioned having 
RaiseError working.  This means that if you try to insert a duplicate 
record the DBI will throw an exception (i.e.: die).  You can use this to 
your advantage.  Try this for make_handle:

    sub make_handle {

        my ($dbh, $username, $password, $URL) = @_;
        my $sth = shift;

        my $sth = $dbh->prepare("INSERT INTO handles (users, passwords)

        my $success = 0;

        # trap any errors that may occur so that if the DBI dies the web
    page doesn't have to
        eval {
            $sth->execute($username, $password);

            # if we got this far then there was no error and we
    succeeded in creating a new entry
            $success = 1;


        # return a status code that says whether we were successful and
    also return any error that may have occurred.
        return $success, $@;

Then when you call make_handle you can see if you were successful and if 
not you can see what kind of error occurred:

    if ($x eq ""){

    elsif ($x eq "Submit"){
      my ($success, $error) = make_handle ($dbh, $username, $password,

      # if we succeeded let the user know
      if ($success) {
      # otherwise we give them an error page
      else {

        # if the error was due to a duplicate entry the message will say so
        if ($error =~ m/duplicate entry/i) {

        # clean up the error message so that the user doesn't have to
    read DBI error talk
          $error = "The username '$username' is already in use. Please
    try again";

        # Then show the welcome page with a message this time so they
    can try again

        # if it's not a duplicate entry we need to tell them that there
    was a db error and chances
        # are it won't help to try again
        else {

    else {

Have fun,

-- Ben

More information about the spug-list mailing list