getting the query from database - Codeigniter - php

I wanted to check whether the username exists in the database,
but Codeigniter is throwing an
Error: Can't use method return value in write context.
The code is as follows:
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if(empty($query->row_array())){
return true;
}else{
return false;
}
}

$result = $query->row_array();
if(empty($result)){
return true;
}else{
return false;
}

try using below code
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if($query->num_rows() > 0){
return true;
}else{
return false;
}
}

It looks like you are trying to validate a form for user registration. If this is the case, then you would be far better off using the built-in form_validation library (https://codeigniter.com/user_guide/libraries/form_validation.html). There is already a built in method that would help you make sure you have unique records (such as the username). So basically, once the form_validation library is loaded, you would need to set the rules for validation. Once rules are set, you can call the run() method, which will produce a bool true/false whether it passes validation or not.
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', "trim|required|is_unique[users.username]");
if($this->form_validation->run() === true) {
//Do something when posted form is validated
} else {
// There were errors or this is the first time
if(validation_errors())
$data['error_message'] = validation_errors();
}
You should use the form validation library to validate any (and usually all) of your forms throughout your application
Hope that helps

First Understand the Error: Can't use method return value in write context.
empty() needs to access the value by reference (in order to check whether that reference points to something that exists).
However, the real problem you have is that you use empty() at all, mistakenly believing that "empty" value is any different from "false".
Empty is just an alias for !isset($thing) || !$thing. When the thing you're checking always exists (in PHP results of function calls always exist), the empty() function is nothing but a negation operator.
Not Coming to your problem, As Scott Miller suggest you can use CodeIgniter validation. And if you want a little advance solution then you can put your validation in the config folder with creating form_validation.php for more detail visit CodeIgniter documentation for validation.
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|is_unique[users.username]'
)
);
And If you want to do it with the query then here is the query:
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
You can use num_rows to get the username exist or not.

Related

CodeIgniter - username and email existence check doesn't work

I'm trying to check whether or not an email or username exists in the database before inserting data into the database. For a reason I do not understand, despite using the email_exists and username_exists functions, when inserting the data, the database throws a field not unique error for username and email fields.
The username_exists and email_exists functions gets any usernames or emails where they match the username or email submitted by the form. The functions then return true if there is a username or email that exists, or false if the opposite. When both functions return false (i.e. username and email don't exist in the database) it inserts the form data into the database.
Any help would be great!
Controller Function
public function register(){
if($this->session->userdata('loggedIn') == TRUE){
$this->session->set_flashdata('error_msg', 'please log out to access this page ');
echo 'Please log out to access this page!...';
sleep(2);
redirect('index.php/user/dashboard');
}
$data['session_data'] = array(
'userID' => $this->session->userdata('userID'),
'loggedIn' => $this->session->userdata('loggedID')
);
$this->load->view('navigation');
$this->load->view('register', $data);
echo 'registration page - ';
if($this->input->post('register')){
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('email', 'email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
$user_details = array(
'username' => strip_tags($this->input->post('username')),
'email' => strip_tags($this->input->post('email')),
'password' => strip_tags($this->input->post('password'))
);
if($this->form_validation->run() == true){
$username_exists = $this->user_model->username_exists($user_details[0]);
$email_exists = $this->user_model->email_exists($user_details[1]);
if($username_exists == false && $email_exists == false) {
$this->user_model->add_user_account($user_details);
echo 'user added successfully: '. $user_details[0];
$this->session->set_flashdata('success_msg', 'SUCCESSFULLY ADDED USER, username and email do not already exist!... ');
sleep(2);
redirect('index.php/user/login');
} else {
echo 'username or email already exists! try again!...';
$this->session->set_flashdata('error_msg', 'ERROR OCCURRED - username or email exists!...');
sleep(2);
redirect('index.php/user/register');
}
} else {
echo 'error occured, try again!...';
$this->session->set_flashdata('error_msg', 'ERROR OCCURRED- something didn\'t work');
sleep(2);
redirect('index.php/user/register');
}
}
}
Model Functions
public function add_user_account($user_details){
$this->db->insert('user_account', $user_details);
}
public function username_exists($username){
$this->db->select('username');
$this->db->from('user_account');
$this->db->where('username', $username);
$query = $this->db->get();
if($query->num_rows() > 0){
return true;
} else {
return false;
}
}
public function email_exists($email){
$this->db->select('email');
$this->db->from('user_account');
$this->db->where('email', $email);
$query = $this->db->get();
if($query->num_rows() > 0){
return true;
} else {
return false;
}
}
$user_details[0] doesn't reference anything as you have non-numerical keys for the user_details array. I assume you mean to access the key username thus you should do $user_details['username'].
Like so:
$username_exists = $this->user_model->username_exists($user_details['username']);
$email_exists = $this->user_model->email_exists($user_details['email']);
To be honest I'm surprised this isn't giving you notice errors.
Further, you could easily make your username/email exists functions into a callback or simply use the is_unique feature of the form_validation library.
Also I'm pretty sure that you can apply strip_tags as a form_validation rule and it will remove the tags in the post variables.
Well to address your question via a means of simplification, you can use is_unique[table.field] as a validation rule.
That way you do not need to write any model methods for checking that your username or email is unique.
So in your form validation rules you can alter your username and email rules to include the is_unique rule.
$this->form_validation->set_rules('username', 'Username', 'required|is_unique[user_account.username]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[user_account.email]');
Note: The 2nd Field is the Form Label and can be anything. In this case I uppercased it. The 1st field IS case sensitive.
As to why your existing code isn't working...
Try getting friendly using var_dump(); or print_r();
i.e.
$username_exists = $this->user_model->username_exists($user_details[0]);
$email_exists = $this->user_model->email_exists($user_details[1]);
// Debug these two and see what they are...
var_dump($username_exists);
var_dump($email_exists);
Now seeing you are using an associative array in setting up
$user_details = array(
'username' => strip_tags($this->input->post('username')),
'email' => strip_tags($this->input->post('email')),
'password' => strip_tags($this->input->post('password'))
);
And then referencing them like
$username_exists = $this->user_model->username_exists($user_details[0]);
Using the above var_dump's should give you an "Aha!!!" moment.
When in doubt var_dump();

Checking Username Availability in Laravel

Is there a way to check if a username is already taken in laravel? I mean I want to check if a username is taken already without submitting the form that means checking the availability of the username while the user is typing. If there is what language should I use? And please cite examples. Thank you!
$count = User::where('userName', 'like', '%Lyka%')->count();
if($count > 0)
{
//username exists
}
else
{
//username doesn't exist
}
or you can validate in laravel validation itself
$rules = array('username' => 'required|unique:user');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
$messages = $validator->messages()->first();
Session::put('msg',$messages);
return Redirect::back();
} else {
// username not exist
}
unique:user => unique from the table called user
username => is the column of the table user
A better approach would be to use laravel validation. Use ajax to send the input to laravel backend. And then somewhere in your controller.
$validator = Validator::make($request->all(), [
'username' => 'unique:users',
]);
And check if it fails
if ($validator->fails()) {
//do whatever you want to do at fail
//possible return appropriate json with error
}
Is there a way to check if a username is already taken in laravel?
Yes, try some PHP like the following:
$count = User::where('userName', '=', 'Lyka')->count();
if($count > 0)
{
//username exists
}
else
{
//username doesn't exist
}
If you want to check asynchronously you would have to write some Javascript and use AJAX to check while the user is filling out the form.
If there is what language should I use?
PHP obviously and Javascript.
Good luck.

Passing Data to view in a Redirect request to prevent double submission

I am trying to prevent double submission through the back button in a simple voting application
I was doing this before. After voting it returns this view
return View::make('votes.votesresults')->with('candidates',$candidates)->with('count',$count);
This passes two variables to votesresult view but unfortunately if someone clicks the back button they can resubmit their votes. I looked around and came across the PRG pattern. Am supposed to use a redirect to prevent this. So i tried this
return Redirect::route('votes.votesresults')->with('candidates',$candidates)->with('count',$count);
Here are my controllers
public function votesuccess()
{
$rules = array(
'name' => 'required'
);
$validator = Validator::make(Input::all(),$rules);
if ($validator->fails()) {
return Redirect::to('votes/index')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$vote = new Vote;
$candidates = Candidate::all();
$candidate_id =Input::get('name');
$candidate = Candidate::find($candidate_id);
$vote = $candidate->votes()->save($vote);
//$count = DB::table('votes')->where('candidate_id','=','$candidate_id')->count();
$count = DB::table('votes')->count();
// redirect
Session::flash('message', 'Successfully Cast your vote!');
//return View::make('votes.voteresults')->with('candidates', $candidates)->with('count',$count);
return Redirect::route('voteresults')->with('candidates', $candidates)->with('count',$count);
}
}
public function voteresult()
{
$candidates = Candidate::all();
return View::make('votes.voteresults');
}
My routes are like this
Route::post('votesuccess', array('as' => 'votesuccess', 'uses'=>'VoteController#votesuccess'));
Route::get('voteresults', array('as' => 'voteresults', 'uses'=>'VoteController#voteresult'));
This does not work because it returns undefined variable: candidates. My results view requires these variables. So how do I implement the PRG pattern correctly such that I prevent double submission while being able to pass data to my view
You are redirecting to the route named voteresults, which is handled by the voteresult function and not the votesuccess function.
In your votesuccess function, you should load the view and include the candidates variable in that view. You can access the candidates variable stored in the session by using Session::get('candidates').
It would help to see you voter results view to see what's going on there, and where/how you've put in logic to avoid duplicate submission. Are you concerned about accidental re-submissions, or just multiple submissions from the same user? If the latter, then you would need to build in some logic that limits a user to only 1 vote. You could do this by check if the user has a related vote.
if ( ! $candidate->votes() ) {
// no votes exist, proceed with storing vote
}
Below is you controller refactored a bit:
public function votesuccess()
{
$rules = array(
'name' => 'required'
);
$validator = Validator::make(Input::all(),$rules);
if ($validator->fails()) {
return Redirect::back('votes/index')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$candidate = Candidate::find(Input::get('name'));
$vote = $candidate->votes()->save(new Vote);
// redirect
Session::flash('message', 'Successfully Cast your vote!');
return Redirect::route('voteresults');
}
}
public function voteresult()
{
$candidates = Candidate::all();
$count = DB::table('votes')->count();
return View::make('votes.voteresults', compact('candidates', 'count'));
}

No user data to use

I am completing my login function for my application and I'm receiving the trying to get property of non object on a few lines. The first one is shown below that does a function call to the is_user_locked method using the object property lock_date inside the user_data object. I understand that this means that at this point their is no user_data to work with so it can not use the properties. I'm curious to know how should I account for this so that I don't abuse using too many nested if statements.
if (count($user_data) == 0) {
$output = array('content' => 'The user was not found in the database!', 'title' =>
'User Not Found');
}
if ($this->is_user_locked($user_data->lock_date)) {
$output = array('content' => 'This user account is currently locked!', 'title' =>
'Account Locked');
}
Any ideas on why this could be? Any and all suggestions would be helpful.
I'm curious to know how should I account for this so that I don't
abuse using too many nested if statements.
How about something like this ?
if( $user_data ) {
// $user_data contains something so let's proceed
if ($this->is_user_locked($user_data->lock_date)) {
$output = array('content' => 'This user account is currently locked!', 'title' => 'Account Locked');
}
} else {
// Nothing in $user_data so throw Exception or display error
$output = array('content' => 'The user was not found in the database!', 'title' =>
'User Not Found');
}
See this link.
if($var): same as $var == NULL.
What seems to be happening is $user_data->lock_date should be $user_data['lock_date']. I'm not 100% sure by the code you posted but it seems you're just referencing an array element incorrectly.
Terinary operators can be used to avoid if statements
$user_data === null ? "it's null" : "otherwise it's not";
i am a huge fan of negative if checks. the idea is that if you do not get what you expect, you immediately exit. this can be getting back a result, or doing a true false check. Of course you are first going to validate the user name using CI form validation. so for example in your model, the method that checks for the user name - if the result is 0, just have it return false. Then in your controller:
// Validate the user name and other form info
// if validation passes, grab the username,
// note the TRUE, that tells CI to run it through XSS clean
$username = $this->input->post( 'username', TRUE ) ;
// if we did NOT get a user back from model, immediately go to new method
if ( ! $user = $this->users_m->_findUser($username) ) {
$this->_userNotFound(); }
// similar, if the user account is locked, go to new method
// if you return an array from model this would be $user['lock_date']
elseif ($this->isUserLocked($user->lock_date) == TRUE) {
// DO NOT try and write messages etc here. put all that in a separate method
$this->_userAccountLocked(); }
else {
// you have a $user and the user is not locked
// its tempting to write a bunch of stuff here
// do not do that. keep it clean, and go to separate method
$this->_displayAccount($user) ; }
Note that i put an underscore before all the method names - CI will automatically make those private.
Also note the Camel case for method names -- versus underscores. some people prefer it.
You could do this:
if (count($user_data) == 0) {
$output = array('content' => 'The user was not found in the database!', 'title' =>
'User Not Found');
} else if ($this->is_user_locked($user_data->lock_date)) {
$output = array('content' => 'This user account is currently locked!', 'title' =>
'Account Locked');
}
Which is pretty much identical to your initial code, but with an else thrown in.

Codeigniter helper function to validation rules

I created a helper for checking if a user id exists in my user database table:
if ( ! function_exists('valid_user'))
{
function valid_user($user_id)
{
$ci=& get_instance();
$ci->load->database();
$ci->db->select('id');
$ci->db->where('id', $user_id);
$ci->db->where('activated', 1);
$ci->db->where('banned', 0);
$ci->db->limit(1);
$query = $ci->db->get('users');
if ($query->num_rows() > 0) //if user exists
{
return TRUE;
}
else
{
return FALSE;
}
}
}
I added the function to my validation rule like so
$this->form_validation->set_rules('user_id', 'User ID', 'required|xss_clean|max_length[11]|is_natural_no_zero|valid_user');
It does not perform the valid_user function. What am I doing wrong here?
In my previous experience, I usually added a validation function (in your case, valid_user) in the same place where the callback is called.
For example, I would put valid_user method in a users_controller where one of the registration methods will invoke the valid_user method.
Also, it seems that, in your set_rules, you have to set callback_valid_user not valid_user according to the Codeigniter user guides.
http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks
$this->form_validation->set_rules('user_id', 'User ID',
'required|xss_clean|max_length[11]|is_natural_no_zero|callback_valid_user');
//note the callback_ ↑

Categories