What potential security risks are present in the code provided?
The code provided is vulnerable to SQL injection attacks as it directly concatenates user input into the SQL query without sanitizing it. To mitigate this risk, we should use prepared statements with parameterized queries to prevent malicious SQL injection attempts.
// Original vulnerable code
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Fixed code using prepared statements
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username=? AND password=?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
Keywords
Related Questions
- Are there any best practices for structuring SQL queries in PHPMyAdmin to handle complex data transformations like pivoting?
- How can PHP beginners convert MySQL timestamps to specific date formats using PHP functions like strtotime and date?
- How can PHP be used to automatically play a sound when there is a change detected in a database?