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

Common pitfalls when inserting data into a database using PHP include not properly sanitizing user input, not using prepared statements to prevent SQL injection attacks, and not handling database connection errors. To avoid these pitfalls, always sanitize user input using functions like mysqli_real_escape_string, use prepared statements with placeholders, and implement error handling for database connections.

// Example code snippet for inserting data into a database using prepared statements and error handling

// Establish database connection
$connection = new mysqli('localhost', 'username', 'password', 'database');

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

// Prepare SQL statement with placeholders
$stmt = $connection->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");

// Bind parameters to placeholders
$stmt->bind_param("ss", $value1, $value2);

// Set parameter values
$value1 = "value1";
$value2 = "value2";

// Execute the prepared statement
$stmt->execute();

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