How can sprintf be used in PHP to prevent SQL injection when querying a database with user input?

To prevent SQL injection when querying a database with user input in PHP, you can use sprintf to properly format the query string and escape any user input values. This helps to ensure that the user input is treated as data rather than executable SQL code, reducing the risk of malicious SQL injection attacks.

$user_input = $_POST['user_input']; // Assuming user input is received via POST

// Using sprintf to format the query string with placeholders for user input
$query = sprintf("SELECT * FROM users WHERE username = '%s'", mysqli_real_escape_string($connection, $user_input));

// Executing the query using the database connection
$result = mysqli_query($connection, $query);

// Processing the query result as needed