What is the recommended method for escaping user input when storing data in a MySQL database using PHP?

When storing user input in a MySQL database using PHP, it is crucial to escape the input to prevent SQL injection attacks. The recommended method for escaping user input is to use prepared statements with parameterized queries. This method separates the SQL query from the user input, ensuring that the input is properly sanitized before being executed.

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");

// Bind the user input to the prepared statement parameters
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);

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