How can prepared statements or escaping be used to prevent SQL injection in PHP code?

SQL injection can be prevented in PHP code by using prepared statements or escaping user input. Prepared statements allow the database to distinguish between code and data, preventing malicious SQL code from being executed. Escaping user input involves sanitizing input data by escaping special characters, making it safe to use in SQL queries.

// Using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Bind parameters
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();

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

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