Shagun Sood
Shagun Sood

Reputation: 153

codeigniter error :Message: Undefined variable: results

I am adding users in a table through CodeIgniter form. Insertion is going fine. but after deleting selected record i am getting undefined variable results. I also defined

 $results = NULL;

in my controller code. What is happening with my code?

Controller code

$results = NULL;
$this->load->model('User');
$form_data['results'] = $this->User->view_table();
$this->load->view('User/User_login', $form_data);

View Code in user_login.php

<?php 
            if(sizeof($results)>0){
                foreach ($results as $row){
                    echo "<tr style='text-align:center';>";
                    echo "<td>".$id=$row->id."</td>";
                    echo "<td>".$row->first_name."</td>";
                    echo "<td>".$row->last_name."</td>";
                    echo "<td>".$row->username."</td>";
                    echo "<td>".$row->email."</td>";
                    echo "<td><a href = ".base_url().'Users/user_edit'.">Edit</a>|<a href=".base_url().'Users/user_delete/'.$id=$row->id.">Delete</a></td>";
                   // echo $id; die();
                echo "</tr>";
            }
            }else{
                echo "no record found";
            }

            ?>

Error

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: results

Filename: User/User_login.php

Line Number: 44

Upvotes: 1

Views: 19929

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

use isset which checks that variable is defined or not

<?php 
        if(isset($results)){
            foreach ($results as $row){
                echo "<tr style='text-align:center';>";
                echo "<td>".$id=$row->id."</td>";
                echo "<td>".$row->first_name."</td>";
                echo "<td>".$row->last_name."</td>";
                echo "<td>".$row->username."</td>";
                echo "<td>".$row->email."</td>";
                echo "<td><a href = ".base_url().'Users/user_edit'.">Edit</a>|<a href=".base_url().'Users/user_delete/'.$id=$row->id.">Delete</a></td>";
               // echo $id; die();
            echo "</tr>";
        }
        }else{
            echo "no record found";
        }

        ?>

isset

The $results you have set this to null but you haven't pass this to view you have passed $form_data to view generally codeigniter converts all the keys passed to view to variable therefore you see undefined message because your $this->User->view_table(); returns nothing and it is assigned to $form_data['results']

Upvotes: 1

Kevin
Kevin

Reputation: 1000

I guess the $this->User->view_table() function sometimes return NULL. Check it.

Upvotes: 0

Related Questions