What are the potential risks of SQL Injection in the provided PHP code?
The potential risk of SQL Injection in the provided PHP code is that user input is directly concatenated into the SQL query without proper sanitization, allowing malicious users to manipulate the query and potentially access or modify sensitive data in the database. To prevent SQL Injection, it is recommended to use prepared statements with parameterized queries to separate the SQL code from the user input.
// Original vulnerable code
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
// Fixed 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();
Related Questions
- What is the purpose of the selected attribute in HTML select options and how does it affect PHP form handling?
- How can PHP be used to update a dataset and display the updated dataset at the top of a list?
- What are the best practices for handling sensitive data like IP addresses in PHP form submissions?