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
- How can the while loop be optimized to prevent getting stuck in PHP MQTT subscriptions?
- How can PHP developers ensure proper encoding and decoding of text, especially when dealing with special characters like Umlauts?
- How can long strings representing images in a MySQL database be converted back into images in PHP?