What are some best practices for handling user registration and code generation in PHP?

Issue: When handling user registration in PHP, it is important to generate a unique code for each user to verify their account. This code should be securely stored and used to confirm the user's identity during the registration process. Code snippet:

// Generate a random unique code for user verification
$verification_code = bin2hex(random_bytes(16));

// Store the verification code in the database along with the user's other information
$query = "INSERT INTO users (username, email, password, verification_code) VALUES ('$username', '$email', '$password', '$verification_code')";
$result = mysqli_query($connection, $query);

if ($result) {
    // Send the verification code to the user via email or SMS
    $message = "Your verification code is: $verification_code";
    mail($email, "Account Verification Code", $message);
    echo "Verification code sent successfully!";
} else {
    echo "Error: Unable to register user.";
}