What are common mistakes when using PHP to insert data into a database and how can they be avoided?

Common mistakes when inserting data into a database using PHP include not sanitizing input data, not using prepared statements to prevent SQL injection, and not handling errors properly. To avoid these mistakes, always sanitize user input, use prepared statements with parameter binding, and implement error handling to catch any issues that may arise during the insertion process.

// Assuming $conn is the database connection object

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

// Prepare and execute a SQL statement using prepared statements
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();

// Check for errors during insertion
if ($stmt->errno) {
    echo "Error: " . $stmt->error;
} else {
    echo "Data inserted successfully";
}

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