essential quint wrote:

I'm writing a login script for a website, and the first subroutine will look up the username. But suppose the username doesnt exist in the database, then what kind of value will MySQL or DBI return? I need it for writing the conditional in the control structure.

There are many ways to invoke DBI, and your answer depends on which DBI method you call and under which return context (void, scalar, or list). See http://search.cpan.org/~timb/DBI/DBI.pm for details.

For example,

 my $val = $dbh->selectrow_array(
     "SELECT username FROM users WHERE username = ?", undef, $username);
 if(!defined($val)) {
    die "DB query failed: $dbh->errstr ." if $dbh->err;
    print "User not found.";
 }
 else { print "The user '$val' does exist."; }

Notice that there are really two ways in which the query can "fail." First, the call itself might not work (e.g. invalid SQL syntax or the database server is down) even though the user might actually exist in the database. Second, the call may work but return no matching user.

If however, you enable "RaiseError" as described in the above link, then the call will throw an exception for you on failure, so the above might simplify to

 my $val = $dbh->selectrow_array(
     "SELECT username FROM users WHERE username = ?", undef, $username);
 if(!defined($val)) {
    print "User not found.";
 }
 else { print "The user '$val' does exist."; }

(Technicality: The above code assumes that there are no rows in the username table having a NULL value in the username field. In this example, this assumption is highly likely to be valid. The issues is that DBI returns undef for NULL values, and this could cause confusion when doing the above "if(!defined($val))" test.)

-davidm




Reply via email to