What are the potential consequences of not properly escaping or sanitizing user input in PHP MySQL queries?
If user input is not properly escaped or sanitized in PHP MySQL queries, it can lead to SQL injection attacks where malicious code is injected into the query, potentially causing data loss, unauthorized access, or other security vulnerabilities. To prevent this, always use prepared statements with parameterized queries or escape user input using functions like mysqli_real_escape_string().
// Using prepared statements to prevent SQL injection
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// process the data
}
$stmt->close();