How can the SQL statement in the provided PHP code be improved to prevent SQL injection attacks?
To prevent SQL injection attacks, the SQL statement in the provided PHP code should use prepared statements with parameterized queries. This involves using placeholders for user input values that are then bound to parameters before execution, preventing malicious SQL code from being injected.
// Original vulnerable code
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
// Improved code using prepared statements
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username=? AND password=?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
Keywords
Related Questions
- What are the advantages and disadvantages of using server-side caching versus browser caching in PHP web development?
- What are some common pitfalls to avoid when setting up an Apache server for PHP development?
- What are some alternative approaches to sending a CSV file to the browser for download in PHP?