How can prepared statements in MySQLi or PDO be utilized to prevent SQL injection in PHP applications, and what are the advantages of using them over traditional methods?

SQL injection can be prevented in PHP applications by using prepared statements in MySQLi or PDO. Prepared statements separate SQL logic from data, allowing the database to distinguish between code and data, thereby preventing malicious SQL injection attacks. This method also automatically escapes special characters in data, providing an additional layer of security.

// Using prepared statements in MySQLi
$mysqli = new mysqli("localhost", "username", "password", "database");

$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = $_POST['username'];
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Process data
}

$stmt->close();
$mysqli->close();