What are the potential security risks in the provided PHP code snippet when interacting with a database?
The potential security risk in the provided PHP code snippet is SQL injection. To prevent this, you should use prepared statements with parameterized queries to sanitize user input before executing them in the database.
// 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
$stmt = $connection->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();
$result = $stmt->get_result();
Related Questions
- How can the code snippet be optimized to improve performance when processing and displaying sorted data from a MySQL database in PHP?
- What potential pitfalls should be considered when implementing a checkout system that involves both online and offline user registration?
- What are some alternative methods to create a confirmation dialog in PHP applications for critical actions like record deletion?