What are common pitfalls when inserting values into a database using PHP and how can they be avoided?

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

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Sanitize user input
$name = htmlspecialchars($_POST['name']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Prepare the SQL statement
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");

// Bind parameters
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);

// Execute the statement
if ($stmt->execute()) {
    echo "Data inserted successfully";
} else {
    echo "Error inserting data";
}