The following codeigniter function takes a (string) parameter and returns the (integer) ID of the row. It works fine if i pass string values, but if integer 0 is passed, it returns ID of first row in database. In principle, it should return the user_id only if the the user_name exists in the database. Since there is no user_name called 0, it should return false.
Can someone tell why it is behaving like this and how it can be fixed?
Thanks.
public function get_user_id($user_name)
{
$this -> db -> select('user_id');
$this -> db -> from('users');
$this -> db -> where('user_name', $user_name);
$this -> db -> limit(1);
$query = $this->db->get();
if ( $query->num_rows > 0 )
{
$row = $query->row();
return $row->user_id;
}
return false;
}
For example:
$user_name = "test"; //works fine, returns id.
$user_name = "0"; //works fine, doesnt return anything
$user_name = 0; //Problem. returns ID of first row.
You should add a test of the kind
if ($user_name == "") return false;to catch this.Apparently
wherewith second argument 0 always matches, e.g. translates into SQLWHERE user_name, rather thanWHERE user_name = "", andWHERE user_nameis short-hand forWHERE user_name != ""— the opposite of what you wanted 🙂Running this test at the beginning saves you a full database query when you’re passed an argument that will necessarily result in
false.