How can one improve the readability and efficiency of PHP code when handling SQL queries?
When handling SQL queries in PHP, it is important to improve readability and efficiency by using prepared statements instead of directly inserting variables into the query string. This helps prevent SQL injection attacks and makes the code easier to read and maintain. Additionally, using functions like mysqli or PDO can streamline the process of interacting with the database.
// Example of using prepared statements with PDO for improved readability and efficiency
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetch()) {
// Process the fetched data
}