What are the potential dangers of not properly escaping special characters in SQL queries in PHP?

Failure to properly escape special characters in SQL queries in PHP can lead to SQL injection attacks, where malicious SQL code is inserted into the query, potentially allowing attackers to access or manipulate the database. To prevent this, it is crucial to use prepared statements with parameterized queries or escape special characters using functions like `mysqli_real_escape_string()`.

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

if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$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 the retrieved data
}

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