[英]codeigniter - if model mysql query fails, send flashdata back to the user
I have a model update function being called by my controller: 我的控制器正在调用模型更新功能:
function update_customer_records( $id, $data )
{
$this->db->where( 'id', $id );
$this->db->update( 'customers', $data );
}
I am simply updating my table. 我只是在更新我的桌子。 if the update fails, example duplicate customer name [unique field] I want to send flashdata back to the user
$this->session->set_flashdata('dbaction', 'Update Failed, possible duplicate Customer Name. Please try again or contact the administrator');
如果更新失败,则示例重复的客户名[唯一字段]我想将flashdata发送回用户
$this->session->set_flashdata('dbaction', 'Update Failed, possible duplicate Customer Name. Please try again or contact the administrator');
So something like this: 所以像这样:
function update_customer_records( $id, $data )
{
$this->db->where( 'id', $id );
$this->db->update( 'customers', $data );
if(update fails){
$this->session->set_flashdata('dbaction', 'Update Failed, possible duplicate Customer. Please try again or contact the administrator');
redirect('masterdata/create_customer', 'refresh');
} else
{
$this->session->set_flashdata('dbaction', 'Update Successful');
redirect('masterdata/create_customer', 'refresh');
}
}
Would this be acceptable or is there a better method for handling this? 这会被接受还是有更好的方法来处理呢?
Thanks in advance, as always. 像往常一样,在此先感谢您。
YOu can use this. 你可以用这个。 returns true if rows affected by the update are greater than 1 else return false
如果受更新影响的行大于1,则返回true;否则返回false
function update_customer_records( $id, $data)
{
$this->db->where( 'id', $id );
$this->db->update( 'customers', $data );
//if affected rows > 0 reutrn true else false
return $this->db->affected_rows() > 0 ? TRUE : FALSE;
}
then on your controller you can use it as 然后在您的控制器上,您可以将其用作
if($this->model->update_customer_records() == FALSE)
{
// set the flashdata here
}else{
// do what you want if update is successful
}
You can use this in your model: 您可以在模型中使用它:
function update_customer_records( $id, $data ) {
$this->db->where( 'id', $id );
if($this->db->update( 'customers', $data ))
return true;
else
return false;
}
function is_exist($customer_name)
{
$query = $this->db->get_where($customers, array('customer_name' => $customer_name), 1);
if ($query->num_rows() > 0)
return false;
else
return true;
}
and in controller use this: 并在控制器中使用此:
if($this->model->is_exist($customer_name)
{
$this->db->update_customer_records( $id, $data );
$this->session->set_flashdata('dbaction', 'Update Successful');
}
else
{
$this->session->set_flashdata('dbaction', 'Update Failed, possible duplicate
Customer. Please try again or contact the administrator');
}
redirect('masterdata/create_customer', 'refresh');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.