Return a variable in my model if the query returns

2020-03-30 06:44发布

问题:

Model

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

Ok So once the model is initialized it queries the db and looks for exactly one match and if found it moves on the else statement. However if not found it will redirect('General_Area/Home');

How do I pass a message in there? In my controller I am returning an object if the query is successful.

And in my view i am 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
    {   
         . . .  

If the $q was not successful I want to be able to echo $error; in the view for the user to see the message.

回答1:

In your Model

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

In the Controller

$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);

In your View

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

Message on redirect

Also if you want to send a message when you redirect to another page you can use in your controller

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

So you can print the message in the view like

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

Read more about Flashdata.