【问题标题】:Return a variable in my model if the query returns true如果查询返回 true,则在我的模型中返回一个变量
【发布时间】:2012-10-04 23:34:37
【问题描述】:

型号

  $q = $this->db->get_where('person', array('p_id' => $p));
  if($q->num_rows()!=1) 
    {
    redirect('General_Area/Home');
    exit();
    }
    else
    {   
         . . . 

Ok 所以一旦模型被初始化,它就会查询数据库并寻找一个匹配项,如果找到它就会移动到 else 语句。但是如果没有找到它会redirect('General_Area/Home');

如何在其中传递消息?在我的控制器中,如果查询成功,我将返回 object

在我看来,我是echo obj->table_col_name

  $q = $this->db->get_where('person', array('p_id' => $p));
  if($q->num_rows()!=1) 
    {
    return $Error = 'You have not been found!...';
    #redirect('General_Area/Home');
    exit();
    }
    else
    {   
         . . .  

如果$q 不成功,我希望能够在视图中echo $error; 让用户看到消息。

【问题讨论】:

  • 一个消息到哪里,在控制器中?
  • 嗯,它应该返回视图,以便用户可以看到它..
  • 我觉得这真的很简单。一定有人知道如何做到这一点?
  • 你想在成功的查询结果中传递带有对象的消息吗?

标签: php codeigniter


【解决方案1】:

在你的模型中

if($q->num_rows()>0)
{
    return array('result'=>$q->result(), 'message'=>'This is a message');
}
return false;

在控制器中

$this->load->model('your_model_name');
$data['query']=$this->your_model_name->model_function_name();
if(!$data['query']['result'])
{
    redirect('General_Area/Home');
    exit();
}
else $this->load->view('your_view_name',$data);

在你看来

if(isset($query))
{
    foreach($query as $row)
    {
        // code goes here to echo columns
    }
    //and message is available as $message so you can print it like
    if(isset($message)) echo $message;
}

重定向消息

另外,如果您想在重定向到另一个页面时发送消息,您可以在控制器中使用

if(!$data['query']['result'])
{
    $this->session->set_flashdata('message', 'your message text here!');
    redirect('General_Area/Home');
    exit();
}

这样你就可以在视图中打印消息了

echo $this->session->flashdata('message');

阅读更多关于Flashdata的信息。

【讨论】:

  • 好的,很棒的答案——很棒的选择。在 flashdata 上 +1 - 非常酷!
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 2018-01-04
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
相关资源
最近更新 更多