What best practices should be followed when working with PHP functions and database queries to avoid redundancy and improve code efficiency?
When working with PHP functions and database queries, it is important to avoid redundancy and improve code efficiency by utilizing prepared statements to prevent SQL injection attacks and by properly organizing and structuring your functions to avoid repeating code. Using functions to encapsulate common database operations can also help reduce redundancy and improve code readability.
// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$result = $stmt->fetch();
// Example of a function to handle database queries
function getUserByUsername($pdo, $username) {
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
return $stmt->fetch();
}
$user = getUserByUsername($pdo, 'john_doe');