Skip to content
PHP Logo

What potential SQL injection vulnerability is present in the provided PHP code and how can it be mitigated?

The potential SQL injection vulnerability in the provided PHP code is that user input ($_POST['username']) is directly concatenated into the SQL query without proper sanitization or parameterization. This can allow malicious users to manipulate the query and potentially access or modify sensitive data in the database. To mitigate this vulnerability, you should use prepared statements with parameterized queries to safely handle user input.

php
// Original vulnerable code
$username = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);

// Mitigated code using prepared statements
$username = $_POST['username'];
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();