What are common pitfalls when inserting data from input fields into a database using PHP?
Common pitfalls when inserting data from input fields into a database using PHP include not sanitizing user input, leaving the application vulnerable to SQL injection attacks, and not validating input data, leading to potential data integrity issues. To solve this, always sanitize user input using prepared statements and parameterized queries to prevent SQL injection attacks, and validate input data to ensure it meets the expected format and constraints.
// Sanitize user input using prepared statements and parameterized queries
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");
$stmt->bindParam(':value1', $_POST['input1']);
$stmt->bindParam(':value2', $_POST['input2']);
$stmt->execute();
// Validate input data to ensure it meets the expected format and constraints
if (filter_var($_POST['input1'], FILTER_VALIDATE_INT) && filter_var($_POST['input2'], FILTER_VALIDATE_EMAIL)) {
// Insert data into the database
} else {
// Handle validation errors
}