How can SQL queries be optimized for efficient data retrieval in PHP applications?
To optimize SQL queries for efficient data retrieval in PHP applications, you can use techniques such as indexing columns used in WHERE clauses, avoiding SELECT *, using prepared statements to prevent SQL injection, and minimizing the number of queries executed.
// Example of optimizing SQL query using prepared statements
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
$users = $stmt->fetchAll();