What are the potential pitfalls of directly inserting user input into a database in PHP?

Directly inserting user input into a database in PHP can lead to SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To prevent this, you should always sanitize and validate user input before inserting it into the database. This can be done by using prepared statements or parameterized queries to securely handle user input.

// Example of using prepared statements to insert user input into a database securely

// Assuming $conn is the database connection object

// Sanitize and validate user input
$userInput = filter_var($_POST['user_input'], FILTER_SANITIZE_STRING);

// Prepare a SQL statement with a placeholder
$stmt = $conn->prepare("INSERT INTO table_name (column_name) VALUES (?)");

// Bind the sanitized user input to the placeholder
$stmt->bind_param("s", $userInput);

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

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