What potential security vulnerability is present in the provided PHP code, and how can it be mitigated?
The potential security vulnerability in the provided PHP code is the use of user input directly in a SQL query without proper sanitization, which can lead to SQL injection attacks. To mitigate this vulnerability, you should use prepared statements with parameterized queries to safely handle user input.
// Original vulnerable code
$mysqli = new mysqli("localhost", "username", "password", "database");
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $mysqli->query($query);
// Mitigated code using prepared statements
$mysqli = new mysqli("localhost", "username", "password", "database");
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username=? AND password=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();