3

lets say the query from my controller is $query.
how to display the data other than using this kind of code?

foreach($query as $row){
echo $row->student_id;
}

any other than this coz the query only have one row
any way that can i access the returned array like this?

$query['student_id'];
1
  • Another alternative is to store the data in a session which can be accessed anywhere on your site without querying every time. Some data ideal for storing in a session is a usernames or user id. codeigniter.com/user_guide/libraries/sessions.html Commented Jun 11, 2011 at 0:41

3 Answers 3

2

let's say your table have the following fields

student_id and student_name

have your model or controller return only one row.

function get_first_student() {

    $query = this->db->select('*')->from('student')-where('student_id','1')->limit(1);
    $data['stuff'] =  $query->row_array(); // or $query->row() which returns an object
    $this->load->view('whatever',$data)

}

then in your view

<p>student name: <?= $stuff['student_name'] ?> </p>
<p>student id: <?= $stuff['student_id'] ?> </p>
Sign up to request clarification or add additional context in comments.

Comments

1

Actually, $query->row() just fetches the first row.

So instead of looping through the result, you could just do:

$student_id = $query->row()->student_id; // (untested)

OR

$row = $query->row();
$student_id = $row->student_id;

Assuming the query will always return a row.

Comments

0

Suppose you are displaying a user's profile. It's good practice to store all database queries in the MODEL. I use this:

CONTROLLER:

$this->load->model('Profile');
$data['row'] = $this->Profile_model->profile_read(); //get profile data
$this->load->view('profile_view', $data); //load data to view

MODEL:

function profile_read()
{
        $this->db->where('user_id', $user_id);
        $query = $this->db->get('user_profiles'); //get all data from user_profiles table that belong to the respective user
        return $query->row(); //return the data    
}

In the model you can have all your other database functions (create, delete, update)

VIEW:

<?php echo $row->name; ?>
<?php echo $row->email; ?>
<?php echo $row->about; ?>
etc

Finally in the view you can echo any rows from the table that belong to the user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.