如何使用戶名在驗證和輸出中唯一,其格式爲「JSON」。其實我使用Codeigniter構建一個應用程序和MongoDB作爲數據庫。我不知道是否在MongoDB中工作的「is_unique」,但我嘗試過,但它不工作。如何在Codeigniter和數據庫中使用「is_unique」是一個mongodb
控制器:
公共職能create_customer(){
$this->load->helper('form');
$this->load->library('form_validation');
if($this->input->post('username') != $original_value) {
$is_unique = '|is_unique[customer.username]'
} else {
$is_unique = ''
}
// field name, error message, validation rules
$this->form_validation->set_rules('first_name', 'Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|xss_clean'.$is_unique);
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('phone_number', 'Phonenumber', 'trim|required|numeric|min_length[10]|max_length[10]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE)
{
header('Content-Type: application/json');
echo json_encode(array('success' => 'FALSE'));
}
else
{
$this->load->model('general/customer');
$new_customer[CUSTOMER_FIRST_NAME]=$this->input->post('first_name');
$new_customer[CUSTOMER_LAST_NAME]=$this->input->post('last_name');
$new_customer[CUSTOMER_EMAIL]=$this->input->post('email_address');
$new_customer[CUSTOMER_USERNAME]=$this->input->post('username');
$new_customer[CUSTOMER_PHONE]=$this->input->post('phone_number');
$new_customer[CUSTOMER_PASSWORD]=$this->input->post('password');
$this->customer->is_unique();
$query = $this->customer->add($new_customer);
header('Content-Type: application/json');
echo json_encode(array('success' => 'TRUE'));
}
}
型號:
public function is_unique()
{
$query = $this->mongo_db->select('username');
$result = mongo_db($query);
$count = mongo_db_num_rows($result);
if ($count>0) {
echo 'Sorry! This Username already exists!';
}
else
{
$insert = $this->mongo_db->insert(CUSTOMER, $new_customer);
return $insert;
}
}
這是我的代碼。我想在應用程序中保持用戶名的唯一性。 請幫我完成申請。
什麼是不工作?你的結果是什麼?您不需要編寫is_unique函數,它內置於CodeIgniter的Form_validation庫中。 – twistedpixel 2014-09-11 02:34:16
其實一個客戶必須有一個用戶名,並且它不應該與其他客戶相同。如果任何客戶在我的應用程序中輸入了一些用戶名,它應該通過拋出錯誤或消息,如「用戶名已存在」。但現在我在我的應用程序中做了一些修改,現在它工作正常。這是我修改後的代碼。 – 2014-09-17 05:59:21