What are the best practices for retrieving and displaying both the group name and group ID from a database in PHP?
When retrieving and displaying both the group name and group ID from a database in PHP, it is best practice to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to separate the database logic from the presentation logic by using a function to retrieve the data and then displaying it in the desired format. Finally, make sure to sanitize the output to prevent any cross-site scripting vulnerabilities.
// Retrieve and display group name and ID from database
$stmt = $pdo->prepare("SELECT group_id, group_name FROM groups");
$stmt->execute();
$groups = $stmt->fetchAll();
foreach ($groups as $group) {
$groupId = htmlspecialchars($group['group_id']);
$groupName = htmlspecialchars($group['group_name']);
echo "Group ID: $groupId, Group Name: $groupName <br>";
}