Store model function return to controller function

混江龙づ霸主 提交于 2019-12-13 09:17:15

问题


I have a model which returns a username of the person that has logged into the website to a controller. I am trying to save the username into a variable which i can user to then insert back into another table, however i am having no luck saving the data. Below is my model and controller classes.

Model:

function is_loggedin()
{
$session_id = $this->session->userdata('session_id');
$res = $this->db->get_where('logins',array('session_id' => $session_id));

if ($res->num_rows() == 1) {
    $row = $res->row_array();
    return $row['name'];
}
else {
    return false;
}
}

Part of my Controller:

public function index()
{
$loggedin = $this->authlib->is_loggedin();

if ($loggedin === false) 
    $this->load->view('login_view',array('errmsg' => ''));
else
{

    $this->load->view('postquestion_view',array('username' => $loggedin));
    $user = $loggedin['username'];
}
}



   public function askquestion()
{

$qtitle = $this->input->post('title');
$qdetails = $this->input->post('details');
$qtags = $this->input->post('tags');
$qcategory = $this->input->post('category');
$quser = $user;

Error:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: user

Filename: controllers/postq.php

Line Number: 47

回答1:


Here the error message is very clear. The variable $user in the last line of the function -action- askquestion() snippet is not defined. Basically, you have to read more about variables scope.

In your current situation, the code of index action should be in constructor and the variable user should be an object property. i.e it should defined globally in your controller's class and then takes its value from the constructor something like the following general demo:

<?php
class Blog extends CI_Controller {

       public $user = false;
       public function __construct()
       {
            parent::__construct();
            // Your own constructor code
       }

       public function askquestion()
       {

              $qtitle = $this->input->post('title');
              $qdetails = $this->input->post('details');
              $qtags = $this->input->post('tags');
              $qcategory = $this->input->post('category');
              $quser = $this->user; //NOTICE THIS LINE
}
?>   


来源:https://stackoverflow.com/questions/27556501/store-model-function-return-to-controller-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!