Forum Moderators: coopster & phranque

Message Too Old, No Replies

querying a database and displaying the right message

         

aline

7:59 pm on May 10, 2003 (gmt 0)

10+ Year Member



I'd like to check that the nickname chosen by users is not similar to someone's else.
At the moment I have the following code:

use CGI ":standard";
$first=param("first");
$surname=param("surname");
$nickname=param("nickname");
$age=param("age");
$personality=param("personality");
$standing=param("standing");
$notes=param("notes");

print"content-type:text/html\n\n";
print"<html>\n";
print"<body bgcolor=\"fffbec\">";

$db=DBI->connect("dbi:mysql:Web") or die"\n Error($DBI::err):$DBI::errstr\n";
$query="select nickname from PERSON";

$a=$db->prepare($query);
$a->execute();
while (@result=$a->fetchrow())
{
for($index=0;$index<@result;$index+1)
{
{if ($nickname!=$result[$index])

{$update="INSERT into PERSON values('$first','$surname','$nickname','$age','$personality','$standing','$notes')";
$s=$db->do($update);
$db->disconnect();
print"<b><font color=\"990000\">Database updated</font color></b>";
}
else
{print"this nickname has already been taken";
}
}
}
}

it is working in the sense that if the same nickname has been found a message appears informing the user that this nickname has really been used but my problem is that the message is repeated a hundreds of time. I guess the problem is with the for loop but I'm unable to find what should be done!

Could anyone help?

Thank you

jpjones

9:25 pm on May 13, 2003 (gmt 0)

10+ Year Member



Hi,

I would suggest changing your SQL query.
At the moment you are requesting every single record from the PERSON table, passing it perl, and having perl loop through every record and attempt a match.

This is very expensive in terms of CPU time and memory. The more records you have, the heavier a burden this routine will place on the server, and the longer it will take to perform.

Instead, do the following (written as an overview, not valid PERL:

Query the database as follows:

$query="select count(*) from PERSON where nickname=$nickname";

If the result!= 0, then the nickname is taken - display "this nickname has already been taken"
Otherwise, result == 0, so add details to database and display "Database updated".

In the above, the SQL server does the hard work, looking for any matches for the nickname. All that is returned to PERL is a single result. This is far far far more efficient.

HTH,
JP