How can SQL injection be prevented in PHP when using MySQLi queries, as discussed in the forum thread?

SQL injection can be prevented in PHP when using MySQLi queries by using prepared statements. Prepared statements separate the SQL query from the user input, preventing malicious SQL code from being executed. This can be done by using placeholders in the SQL query and binding the user input to those placeholders.

// 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
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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