How can PHP developers ensure data integrity and prevent SQL injection vulnerabilities when writing SQL queries for database operations?

To ensure data integrity and prevent SQL injection vulnerabilities when writing SQL queries in PHP, developers should use prepared statements with parameterized queries. This approach separates the SQL query logic from the 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 parameters
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

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

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

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

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}