Mysql – Prevent duplicate entries

MySQLPHP

I have log in form with Username and Password.

$con=mysqli_connect(LOGINDETAILS);
/*if (!$con) {
die("Can not connect: " . mysql_error());
}
*/

$Username = $_POST['Username'];

$pswd = $_POST['pswd'];
$pswd = md5($pswd); 

$sql="INSERT IGNORE INTO CyberSecurity (pswd, Username) 
VALUES('$pswd', '$Username')";

mysqli_query($con,$sql);
echo "The password that you provided has been stored in our database for research purposes.";
mysqli_close($con);
?>

I tried using the INSERT IGNOREbut it stills saves the password even though its the exact same one.

Best Answer

INSERT and INSERT IGNORE add a new row unless the row specifies a duplicate for some PRIMARY or UNIQUE key on the table. The only difference is whether the "duplicate key" is an error or ignored.

Do you want one row per user? Or can the user provide many passwords? In the former case, PRIMARY KEY(username); in the latter, PRIMARY KEY(username, password).

Do you want the user to be able to change his password? Then consider:

INSERT INTO CyberSecurity (username, password)
    VALUES ('$username', '$password')
    ON DUPLICATE KEY UPDATE password = '$password';

But... In any case escape both the username and password, else a username such as O'Brien will blow up your program. (And a hacker can quickly take over your machine by quickly discovering you have failed to escape stuff from $_POST.)