What are the best practices for handling user registration data in PHP to ensure no duplicate entries are made in the database?
To ensure no duplicate entries are made in the database when handling user registration data in PHP, it is best practice to perform a check before inserting new data to see if a user with the same email or username already exists. This can be done by querying the database to search for existing entries that match the new data being inserted. If a match is found, the registration process should be halted and an error message should be displayed to the user.
// Check if user with the same email already exists
$email = $_POST['email'];
$query = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0) {
echo "User with this email already exists";
exit();
}
// Proceed with user registration if no duplicate entry found
// Insert user data into the database
$username = $_POST['username'];
$password = $_POST['password'];
$insert_query = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
mysqli_query($conn, $insert_query);
echo "User registered successfully";