简体   繁体   中英

can't send data from controller to view in a codeIgniter project

I'm trying to send data from my controller to the view. Here is how I do: In the controller:

function getAllProjects() 
    {
      $where= array('id_user'=>$this->session->userdata('id_user'));
      $result=$this->expenses_model->get_all('projets', $where);//get_all returns an array
      echo json_encode ($result);
      return $result;
    }

function index (){
                       $data['all_projects']= $this->getAllProjects();
                       $this->session->set_userdata('id_user', 28);
                       $this->load->view('layout/public/header');
                       $this->load->view('content/public/profil/modules/expenses',$data);
                       $this->load->view('layout/public/footer');
                     }

echo json_encode $data returns a correct result) in the controller but I don't know how to do to display it in the view. I tried:(in the view)

<label><strong>Sur le projet</strong></label>
       <select class="span4" id="projet" name="projet">
    <?php 
        if (isset($all_projects) && ! empty($all_projects))
            {  echo "there is some projects"; //is not printed
            foreach ($all_projects as $project){
            echo  "<option value=".$project['id_projet'].">".$project['titre']."</option>";   }
           else  {
                 echo "<option value='0'>No projects</option>";
                               }

But it does not show anything in the drop down list "projects" What I am doing wrong? Could anyone help me please?

mysql_query() returns a resource and you're handing that to $this->load->view(); as the second parameter. If you dig into the underlying CodeIgniter source, you'll find that CodeIgniter does not know how to deal with Resources as this parameter - only Arrays and Objects.

Please refrain from using mysql_query() and it's friends. As per PHP official documentation :

Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used.

More importantly than this, if you're using CodeIgniter on-top of PHP, use the Database Class in conjunction with the Active Record Class to perform database queries. Hell, even use Datamapper ORM - please don't use mysql_query() or friends.

I changed the foreach like this and it worked :

foreach ($all_projects as $project)
    {
            echo  "<option value=".$project->id_projet.">".$project->titre."</option>";
                                    }

Thank you for your answers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM