What are some best practices for preventing SQL injection attacks in PHP applications?
SQL injection attacks can occur when user input is not properly sanitized before being used in SQL queries, allowing malicious users to manipulate the query and potentially access or modify sensitive data. To prevent SQL injection attacks in PHP applications, it is important to use parameterized queries or prepared statements to separate the SQL query from user input. Example PHP code snippet using prepared statements to prevent SQL injection attacks:
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare SQL statement with placeholders
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set user input
$username = $_POST['username'];
// Execute the query
$stmt->execute();
// Fetch results
$result = $stmt->get_result();
// Process results
while ($row = $result->fetch_assoc()) {
// Output data
echo "Username: " . $row['username'] . "<br>";
}
// Close statement and connection
$stmt->close();
$conn->close();