Skip to content
PHP Logo

What are some best practices for securing PHP applications against SQL injection attacks when handling user input?

SQL injection attacks occur when user input is not properly sanitized, allowing malicious SQL queries to be executed. To prevent this, developers should use prepared statements and parameterized queries to handle user input securely.

php
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the parameter
$stmt->bindParam(':username', $_POST['username']);

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

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