How can the code snippet be improved to adhere to better coding practices, such as separating login logic from user ID retrieval logic in PHP?
The code snippet can be improved by separating the login logic from the user ID retrieval logic. This separation helps in keeping the code modular, easier to read, and maintain. To achieve this, we can create a separate function for user ID retrieval that takes the username as a parameter and returns the corresponding user ID.
function getUserIdByUsername($username, $db) {
$query = "SELECT id FROM users WHERE username = :username";
$stmt = $db->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
$result = $stmt->fetch();
return $result['id'];
}
function login($username, $password, $db) {
// Login logic here
}
// Example usage
$db = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
$username = "john_doe";
$userID = getUserIdByUsername($username, $db);
Related Questions
- What are the potential reasons for the scrollbars not appearing in a popup window despite setting "scroll=yes" in PHP code?
- What is the significance of using the value attribute in HTML <option> tags when working with PHP?
- What best practices should PHP developers follow when working with SQL queries to ensure optimal performance and security?