0

I get the error shown below when I tried to loop my data/value in my View page.

A PHP Error was encountered Severity: Notice

Message: Undefined variable: tasks

Filename: pages/all.php

Line Number: 2

application/controllers/task.php

public function show() {
      $data['tasks'] = $this->Tasks_model->show_task()->result();
      $this->load->view('pages/all', $data);
}

application/models/Tasks_model.php

public function show_task() {
     return $this->db->get('task');
}

application/views/pages/all

<?php
    foreach($tasks as $task) {
?>
    <span><?php echo $task->title ?></span>
<?php } ?>
Dave
  • 5,108
  • 16
  • 30
  • 40
cantdocpp
  • 350
  • 7
  • 18
  • `return $this->db->get('task')->result();` – Masivuye Cokile Feb 22 '19 at 15:25
  • @MasivuyeCokile still the same error – cantdocpp Feb 22 '19 at 15:32
  • Before `foreach`, always check if that foreach array exists or not. `if( isset($tasks) && ( is_array($tasks) && count($tasks)>0 ) ) { //foreach code here }`. Also by initially, you can set `$data['tasks'] = array();` in first line of `function show()`. – G_real Feb 22 '19 at 15:44
  • thx @VirenPanchal , you help me with my error. But now, i can't loop my data. How do i get the things inside the array ? – cantdocpp Feb 22 '19 at 16:05
  • @BeingShame In controller `function show()`, see what you are getting `/*echo"
    "; print_r($this->data['tasks']); die();*/` and print results accordingly in View foreach loop.
    – G_real Feb 22 '19 at 16:08
  • Still can't display the data. I think, i don't understand your explanation enough @VirenPanchal – cantdocpp Feb 22 '19 at 16:25
  • Please uncomment this `/*echo"
    "; print_r($tasks); die();*/` in view file and see what you are getting. After getting desired array comment it again.
    – G_real Feb 22 '19 at 16:28
  • i get "Undefined variable: tasks" error again after using your code @VirenPanchal – cantdocpp Feb 22 '19 at 16:34
  • Controller => `public function show() { $data['tasks'] = array(); $data['tasks'] = $this->Tasks_model->show_task()->result(); $this->load->view('pages/all', $data); }` View => `0 ) ) { //echo"
    "; print_r($tasks); die();
        foreach($tasks as $task) {
    ?>
        title ?>
    `
    – G_real Feb 22 '19 at 16:39
  • there's no error, but i still can't get the loop data from the tasks. it's still empty. sorry @VirenPanchal – cantdocpp Feb 22 '19 at 16:47

0 Answers0