What are the best practices for preventing SQL injection attacks in PHP?
SQL injection attacks occur when malicious SQL statements are inserted into input fields, allowing attackers to manipulate the database. To prevent SQL injection attacks in PHP, it is important to use prepared statements with parameterized queries. This approach separates SQL code from user input, making it impossible for attackers to inject malicious code.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL statement with placeholders
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
// Set parameters and execute the statement
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the retrieved data
}
// Close the statement and connection
$stmt->close();
$conn->close();