How can SQL injection vulnerabilities be mitigated when using mysqli_query in PHP?

SQL injection vulnerabilities can be mitigated when using mysqli_query in PHP by using prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable code, preventing malicious SQL injection attacks.

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

// Prepare a parameterized query using placeholders
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters and execute the query
$stmt->bind_param("s", $username);
$username = $_POST['username'];
$stmt->execute();

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Handle the data
}

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