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
- Are there any best practices for organizing your workspace when programming in PHP to optimize efficiency?
- How can the SQL query in the VideosGateway class be optimized for better performance when searching for a specific artist in the database?
- In PHP, why can only values be bound as parameters and not column names?