I want to display all data from a table in tcpdf but this code returns me the last id.
$students = $this->db->get_where('enroll', array(
'class_id' => $class_id ,
'year' => $running_year
))->result_array();
foreach($students as $row):
$id = $this->db->get_where('student', array(
'student_id' => $row['student_id']
))->row()->student_id;
$nume = $this->db->get_where('student', array(
'student_id' => $row['student_id']
))->row()->name;
endforeach;
$html =<<<EOD
$id <br/>
$nume
<br/>
I expect to view
id1
name1
id2
name2
... Display the last id but from the first to the penultimate is not displayed. In PHP work very well the code that I provided below.
<?php
$students = $this->db->get_where('enroll' , array(
'class_id' => $class_id ,
'year' => $running_year
))->result_array();
foreach($students as $row):
?>
<tr>
<th class="stil">
<?php echo $count++;?></th>
<td class="stil"><?php
echo $this->db->get_where('student' , array(
'student_id' => $row['student_id']
))->row()->student_id;
?></td>
The PHP generates a page with some results.
There are many things wrong with the current code. First off, you're overwriting your $id
and $nume
variables on each iteration so after the loop, they will only contain the values from the last iteration (last row).
You're also making many unnecessary queries. In your loop, you're making the same exact query for every column you want. You could just fetch the row and reuse the result object. But better yet, you could even just create one single db-query before the loop, joining the enroll
and student
-tables.
I haven't used CodeIgniter for years, but here's some code that should be close enough to demonstrate what you should be doing instead:
// Get all the data using JOIN between the student and enroll tables
$this->db->select('student.*');
$this->db->from('enroll');
$this->db->join('student', 'student.student_id = enroll.student_id');
$this->db->where('enroll.class_id', $class_id);
$this->db->where('enroll.year', $running_year);
$students = $this->db->get()->result();
// Create our result variable so we can append to it
$html = '';
foreach($students as $row):
// Append the current row to the result variable
$html .= $row->student_id . '<br />';
$html .= $row->name . '<br />';
endforeach;
// Now you can echo the $html variable
echo $html;