How can PDO::quote be used for escaping in PHP when generating dynamic SQL for inserts?

When generating dynamic SQL for inserts in PHP, it is important to properly escape the values to prevent SQL injection attacks. The PDO::quote function can be used to escape and quote the values before inserting them into the database. This function adds quotes around the value and escapes special characters, making it safe to include in the SQL query.

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

// User input data
$userInput = "John Doe";

// Escape and quote the user input
$escapedInput = $pdo->quote($userInput);

// Generate the SQL query with the escaped input
$sql = "INSERT INTO users (name) VALUES ($escapedInput)";

// Execute the query
$pdo->exec($sql);