Skip to content
PHP Logo

How can SQL injection attacks be prevented when querying a database in PHP?

SQL injection attacks can be prevented by using prepared statements with parameterized queries in PHP. This method ensures that user input is treated as data rather than executable SQL code, thus protecting the database from malicious queries.

php
// Establish a database connection
$conn = new PDO("mysql:host=localhost;dbname=myDB", $username, $password);

// Prepare a SQL query using a parameterized statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = :username");

// Bind parameters
$stmt->bindParam(':username', $username);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();