Duplicate entries with one command?

I have a script where I want a record for each user, but only one record for each user, but somehow, randomly, it inserts duplicate records for some users?

Here is what i got.

$sql = mysql_query("SELECT * FROM ".$prefix."_userstrings WHERE fk_player_id=$playerid");
$row = mysql_fetch_assoc($sql);

if(!$row){
	$sql = mysql_query("INSERT ".$prefix."_userstrings (fk_player_id,timestamp,active,thestring) VALUES ($playerid,$timestamp,1,'$dbstring')");
	mysql_close($con);
	exit;
} else {
	$sql = mysql_query("UPDATE ".$prefix."_userstrings SET timestamp = $timestamp, active=1, thestring='$dbstring' WHERE fk_player_id=$playerid");
	mysql_close($con);
	exit;
}

I have tried with the exit and mysql_close() but still the same. What can i do to make sure that I don’t get duplicate inserts?

Thanks in advance :slight_smile:

Put a unique index on fk_player_id and then use the INSERT … ON DUPLICATE KEY UPDATE syntax.

And an advice: since the mysql_ database extension is becoming deprecated, you might want to take a look at [URL=“http://www.php.net/manual/en/book.mysqli.php”]mysqli or [URL=“http://www.php.net/manual/en/book.pdo.php”]pdo