How can you ensure that your PHP code is secure and not vulnerable to SQL injection attacks when interacting with a database?

To ensure that your PHP code is secure and not vulnerable to SQL injection attacks when interacting with a database, you should use prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious SQL injection attacks.

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

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

// Bind parameters to placeholders
$stmt->bindParam(':username', $_POST['username']);

// Execute the prepared statement
$stmt->execute();

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