Home » Php » php – Can't read data that send from controller to view by foreach

php – Can't read data that send from controller to view by foreach

Posted by: admin February 25, 2020 Leave a comment

Questions:

The $results that send to the view is undefined

public function action(){
        // if($this->input->post('data_action'))
        // {
        //  $data_action = $this->input->post('data_action');
        //  if($data_action=="fetch_all")
        //  {
                $api_url = "https://jsonplaceholder.typicode.com/users";

                $process = curl_init($api_url); //your API url
                curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
                $return = curl_exec($process);
                curl_close($process);
                $results=json_decode($return);
                //finally print your API response

                $this->load->view('masterPartner',$results);
                //print_r($result);
            //  }
            // }

and this is the view

<?php foreach($results as $result)
                      { ?>
                        <tr>
                        <th scope="row"><?php echo $result->id ?></th>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td><a class="btn btn-success " style="margin-right:5px"href="/Crudview/index.php/edit-partner" role="button">Edit</a><a class="btn btn-danger" href="/Crudview/index.php/viewApi" role="button">Delete</a>
                        </tr>
                        <?php } ?>

the first error

A PHP Error was encountered Severity: Notice

Message: Undefined variable: results

Filename: views/masterPartner.php

Line Number: 115

Second error

A PHP Error was encountered Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/masterPartner.php

Line Number: 115

How to&Answers:

It is because $results does not exist in the view. It is expecting $results to be passed in via an array.

To pass that in you would need to change your current code

From

$results=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$results);

To

$data['results']=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$data);

So now $results is accessible in your view.