What common mistakes can lead to data not being written to a database in PHP registration forms?

One common mistake that can lead to data not being written to a database in PHP registration forms is not properly connecting to the database or not selecting the database before attempting to insert data. Another mistake is not properly sanitizing user input, which can lead to SQL injection attacks or errors when inserting data. Additionally, not checking for errors when executing the SQL query can also prevent data from being written to the database.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sanitize user input
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

// Insert data into the database
$sql = "INSERT INTO users (username, email) VALUES ('$username', '$email')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the connection
$conn->close();