连接控制器中的变量

I'm trying to generate an examKey for each student in my project. I wanted to concatenate $coursecode & 3 random characters to each student_no in the database to produce a key (e.g CMSC11-asd1212345).I have six student_no in the column but the only student_no that is appended is the one in the last row. Here is my controller:

public function addExamKey($exam_no){

    $this->load->model('exam_model');           
    $coursecode = $this->exam_model->loadCourseCode($exam_no);

    $stdNo = $this->loadStudentNo($exam_no);

    //var_dump($stdNo);

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    $charactersLength = strlen($characters);
    $randChar = '';
        for ($i = 0; $i < 3; $i++) {
            $randChar .= $characters[rand(0, $charactersLength - 1)];
        }

    foreach ($stdNo as $row) {

        $examKey = $coursecode.'-'.$randChar.$row->student_no; 

    }


    $this->exam_model->insertExamKey($examKey,$exam_no);

}

public function loadExamKey($examNo){
    $data = $this->addExamKey($examNo);
    $this->load->view('exam_key', $data);
}

And here is my model:

public function getStudentNo($examNo){

    $this->db->select("student.student_no");
    $this->db->from("student");
    $this->db->join("subject", 'subject.classCode = student.classCode');
    $this->db->join("exam", 'exam.course_id = subject.course_id');
    $this->db->where("exam.exam_no", "$examNo");
    $query = $this->db->get();

    $result =  $query->result();


    if($query->num_rows() > 0){

        return $result;
    }
    else{
        return false;
    }
}

So how can I concatenate the $coursecode and 3 random characters to each student_no?

I have tried to use var_dump() to see if my query returns all the student_no and it perfectly return it all.