How can PHP developers ensure the security and efficiency of their database queries when working with user input?

PHP developers can ensure the security and efficiency of their database queries when working with user input by using prepared statements and parameterized queries. This helps prevent SQL injection attacks and ensures that user input is properly sanitized before being executed in the database. Additionally, developers should validate and sanitize user input before using it in queries to further enhance security.

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

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

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

// Loop through the results and do something with them
foreach ($results as $row) {
    // Do something with the data
}