Obviously you must already have some way to identify users
uniquely (e.g. email address, etc.) Although you say nothing
about the database schema you are using, conceptually there
is nothing hard about enforcing a UNIQUE constraint on the
user ID in a "master" table. Having done this, the only thing
left to do is to detect the database error when you try to
insert a conflicting row, and writing some kind of meaningful
error message.
Using PostgreSQL for example:
create table test ( user_id text unique, test_id text );
Now you can say:
pg_exec($conn, 'begin' );
// must do this inside a transaction!
if (!($result = @pg_exec ($conn,
"insert into test values ( 'me_again', 'php_database' ) ")))
{
if ( strpos( $php_errormsg,
'Cannot insert a duplicate key' ) > 0)
{
echo "Sorry, you've already taken this test!"