How can the use of prepared statements in mysqli be beneficial in preventing SQL injections in PHP?

Using prepared statements in mysqli can be beneficial in preventing SQL injections in PHP because it allows the database to distinguish between the actual SQL query and the user input. This means that user input is treated as data and not as part of the SQL query, reducing the risk of malicious SQL injection attacks.

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL statement with a placeholder for user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind the user input to the placeholder
$stmt->bind_param("s", $username);

// Set the user input
$username = $_POST['username'];

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

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

// Process the results as needed
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close the statement and the database connection
$stmt->close();
$mysqli->close();