prepare(" SELECT COUNT(DISTINCT challenge_id) AS completed FROM challenge_submissions WHERE student_id = ? AND is_correct = 1 "); $stmt->bind_param("i", $student_id); $stmt->execute(); $result = $stmt->get_result()->fetch_assoc(); $completed = $result['completed']; // Rule: 5 challenges if ($completed >= 5) { // Check already issued? $check = $conn->prepare(" SELECT id FROM certificates WHERE student_id = ? AND certificate_type = 'Participation' "); $check->bind_param("i", $student_id); $check->execute(); $checkResult = $check->get_result(); if ($checkResult->num_rows == 0) { // Issue certificate $insert = $conn->prepare(" INSERT INTO certificates (student_id, certificate_type, track_name) VALUES (?, 'Participation', ?) "); $insert->bind_param("is", $student_id, $track); $insert->execute(); } }