How do I check if a database row exists using DBD::mysql and Perl?

Gurzo picture Gurzo · Nov 14, 2010 · Viewed 8.6k times · Source

I'm working with a MySQL database and need to check if a row is already there before deciding which queries to run.

The table I'm working on is something like this:

player(playerid, nickname, data1, data2, data3)

Where "playerid" is an auto-incremented number and "nickname" is unique.

I tried some queries with COUNT, COALESCE, fetch->rows, etc.. and got nowhere. I already saw this question, but couldn't solve anything.

Answer

DVK picture DVK · Nov 14, 2010

Could you please post the specific query with SELECT COUNT(*) that didn't work and what the problem was?

The query should be modeled upon this answer: How do I know how many rows a Perl DBI query returns?

Assuming your "row is already there" definition is "the player with the given nickname is there", the query would be:

my $th = $dbh->prepare(qq{SELECT COUNT(1) FROM player WHERE nickname='$nickname'});
$th->execute();
if ($th->fetch()->[0]) {
    ....
} # Code stolen shamelessly from the link above