Codeigniter: Improve code check function
I have the following function that checks to make sure the code entered matches one in a database.
If it does, it adds one credit to the开发者_运维百科 user, and subtracts one from the corresponding row.
else if ($code_enter != NULL){
$code_check = $this->CI->db->select('code')->from('be_coupons')->where('code', $code_enter)->limit(1)->get();
$credits_list = $this->CI->db->select('*')->from('be_coupons')->where('code', $code_enter)->limit(1)->get();
if ($code_check->row() && $credits_list->row()->credits > 0){
$data['credits'] = ($this->CI->db->select('credits')->where('user_id', $id)->get('be_user_profiles')->row()->credits + 1);
$datas['credits'] = ($this->CI->db->select('credits')->where('code', $code_enter)->get('be_coupons')->row()->credits - 1);
$this->CI->db->update('be_coupons', $datas, array('code' => $code_enter));
$this->CI->home_model->update('UserProfiles',$data, array('user_id' => $id));
flashMsg('success',"WOOT");
redirect('home','location');
}
else if ($code_check->row() && $credits_list->row()->credits < 0){
flashMsg('warning','The code you entered is no longer valid.');
redirect('home/addCredit','location');
}
else{
flashMsg('warning','The code you entered is not valid. Check your entry and try again.');
redirect('home/addCredit','location');
}
}
This code works, but I believe I'm being redundant. Could you streamline this, and make it more elegant? Thanks!
shin is correct, this db work should be done in the model.
You can make it even more efficient by reducing the syntax and updating inline.
- select('*') is default, if you dont use select() it will SELECT * for you.
- from('be_coupons')->get() can be get('be_coupons').
Instead of getting something just to count there is one, you can do:
$check = $this->CI->db->where('code', $code_enter)->count_all_results('be_coupons') > 0; // bool true/false
And instead of fetching a number, incrementing in PHP and updating, just do this:
$this->db->set('field', 'field + 1', FALSE);
$this->db->update('table');
The FALSE is important, otherwise it will treat the 2nd param as a field and escape it as:
SET field = "field + 1".
Can you create function for these and call them in your function?
function somename(){$this->CI->db->select('code')->from('be_coupons')->where('code', $code_enter)->limit(1)->get();
return data;}
function othername(){
$credits_list = $this->CI->db->select('*')->from('be_coupons')->where('code', $code_enter)->limit(1)->get();
return data;}
function again anotherone(){
($this->CI->db->select('credits')->where('user_id', $id)->get('be_user_profiles')->row()->credits + 1);
}
etc.
Then in you function,
else if ($code_enter != NULL){
$code_check = $this->somename();
$credits_list = $this->othername();
if (
...
精彩评论