How can PHP developers ensure the integrity and security of their database queries when using user input?

PHP developers can ensure the integrity and security of their database queries when using user input by using prepared statements with parameterized queries. This helps prevent SQL injection attacks by separating SQL code from user input data. Additionally, developers should sanitize and validate user input to ensure it meets expected criteria before executing any database queries.

// Establish 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 user input to the prepared statement
$stmt->bindParam(':username', $_POST['username']);

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

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