Zoee
Zoee

Reputation: 5

how to use json_encode to fetch data from database

I Have 2 table that I want to join them and fetch some data like this I have one student with multiple grade

   {
    "student": {
    "studentID": "2",
    "Name": "s1",
    "age": " 12",
    "grade": [
    {
      "GradeID": "2"
    },{
      "GradeID": "3"
    }
]
  }

I fetch this data from two query in a function in my model and then use json_encode in my controller for my output but I have this

{
  "student": {
    "studentID": "2",
    "Name": "s1",
    "age": " 12"
},
    "grade": [
    {
      "GradeID": "2"
    },{
      "GradeID": "3"
    }
]
  }

and now I don't know how to use json_encode for the first format. thanks

my model(student):
 function get_student_id($id)
    {
        $student['student']=
            $this->db->select('tbl_student.*')
                 ->from('tbl_student')
                 ->where('tbl_student.SID',$id)
                 ->get()->row();

        $student['grade']=
            $this->db->select('tbl_grade.GradeID')
                ->from('tbl_grade')
                ->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
                ->where('tbl_student.SID',$id)
                ->get()->result();



        return $student;
}

my controller:

public function get_student_id()
    {

        $id = $input['one'];
        $this->load->model('student');
        $temp=$this->student->get_student_id($id);
        $output= json_encode($temp);

        die($output);

    }

Upvotes: 1

Views: 210

Answers (1)

Pacio
Pacio

Reputation: 543

You just have to structure the array you're returning from the model correctly. You're putting everything inside two subarrays called student and grade, which are inside the outer array student. Try this:

my model(student):
 function get_student_id($id)
    {
        $student=
            $this->db->select('tbl_student.*')
                 ->from('tbl_student')
                 ->where('tbl_student.SID',$id)
                 ->get()->row();

        $student['grade']=
            $this->db->select('tbl_grade.GradeID')
                ->from('tbl_grade')
                ->join('tbl_sudent','tbl_grade.StudentID=tbl_sudent.SID')
                ->where('tbl_student.SID',$id)
                ->get()->result();



        return $student;
}

I'm not totally certain you want to call get->row() on the first query, if that doesn't work try get->row_array()

Upvotes: 1

Related Questions