Skip to content
PHP Logo

What security risks are present in the current PHP script and how can they be mitigated to prevent SQL injection attacks?

The current PHP script is vulnerable to SQL injection attacks because it directly interpolates user input into SQL queries, making it possible for malicious users to manipulate the queries. To mitigate this risk, we should use prepared statements with parameterized queries to separate the SQL code from the user input, preventing any potential injection attacks.

php
// Original vulnerable code
$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);

// Mitigated code using prepared statements
$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();