What are the best practices for handling user input and database interactions in PHP to prevent errors like inserting incorrect values into the database?

When handling user input and database interactions in PHP, it is essential to validate and sanitize user input to prevent SQL injection attacks and to ensure that only correct values are inserted into the database. One way to achieve this is by using prepared statements with parameterized queries to safely interact with the database.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Validate and sanitize user input
$userInput = $_POST['input'];
$filteredInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("INSERT INTO mytable (column_name) VALUES (:value)");
$stmt->bindParam(':value', $filteredInput, PDO::PARAM_STR);

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