What are common pitfalls when using sprintf in PHP for SQL queries?

Common pitfalls when using sprintf in PHP for SQL queries include not properly escaping user input, leading to SQL injection vulnerabilities. To avoid this, always use prepared statements with parameterized queries instead of directly inserting user input into the SQL query string.

// Example of using prepared statements with parameterized queries to avoid SQL injection

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

// Prepare the SQL query with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

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

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

// Fetch the results
$results = $stmt->fetchAll();

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}