So I am just getting started with PHP/MySQL, and I have been having an issue when running the following code that attempts to insert data into a table. The error is being caused because I have the username column set to be unique and the username "TEST" has already been used. Is there a way that I could write an if statement to catch only the error that occurs when a duplicate entry is created?
$sql = "INSERT INTO users (username, password, email)
VALUES ('$_SESSION[username]', '$_SESSION[password]', '$_SESSION[email]')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";}
else {echo "Error: " . $sql . "<br>" . $con->error;}
The error I'm getting is:
Error: INSERT INTO users (username, password, email) VALUES ('TEST', 'password', 'example@gmail.com') Duplicate entry 'TEST' for key 'username'
You can try to use INSERT IGNORE INTO users ... your query .... It will not create an error and after query you should check the value of $con->affected_rows - if it is equal to 0 then there was a duplicate (insert statement was failed and ignored).
Check it, I may be not correct, but as far as I remember, it should work.