What are some best practices for efficiently handling insert, update, and delete operations in PHP when values are dependent on user input?

When handling insert, update, and delete operations in PHP where values are dependent on user input, it is important to sanitize and validate the user input to prevent SQL injection attacks and ensure data integrity. Using prepared statements with parameterized queries is a best practice to securely handle user input in database operations.

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

// Sanitize and validate user input
$userInput = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("INSERT INTO mytable (column_name) VALUES (:user_input)");

// Bind the sanitized user input to the parameter in the query
$stmt->bindParam(':user_input', $userInput);

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