存储模型函数返回控制器函数 [英] Store model function return to controller function

查看:143
本文介绍了存储模型函数返回控制器函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,它返回已登录网站的用户的用户名到控制器。我试图将用户名保存到一个变量,我可以用户然后插回到另一个表,但我没有运气保存数据。下面是我的模型和控制器类。

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.

模型:

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;
}
}

我的部分控制器:

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;

错误:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: user

Filename: controllers/postq.php

Line Number: 47


推荐答案

这里的错误信息很清楚。未定义函数的最后一行中的变量 $ user - askquestion()片段。基本上,您必须详细了解 变量范围

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.

在您当前的情况下,索引操作的代码应该在 构造函数 ,变量 user 应为对象属性。即它应该在你的控制器类中定义,然后从构造函数中获取它的值,如下面的一般演示:

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
}
?>   

这篇关于存储模型函数返回控制器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆