What security considerations should be taken into account when querying a database in PHP to prevent SQL injection attacks?

To prevent SQL injection attacks when querying a database in PHP, you should always use prepared statements with parameterized queries. This technique separates SQL code from user input, preventing malicious input from altering the query structure. Additionally, input validation and sanitization should be performed to ensure that only expected data is passed to the database.

// Establish a database connection
$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 parameter and execute the query
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

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