Unknown column $user_id in WHERE clause

I am building an application for a charity in CodeIgniter 3, and have run into a problem trying to access the church name assigned to a given logged in user.

This is my method in the user_model.php:

/*
    * get church name for a given user
    */
    public function get_user_church($user_id) {

         // Test to make sure value of $user_id is being passed to this method
         // echo $user_id;
        //  exit;

    $query = $this->db->query(
                                'SELECT users.id, churches.name AS church_name
                                FROM users
                                JOIN churches ON users.church_id = churches.id
                                WHERE users.id = $user_id'        
                            );
                
        return $query->result();
        
    }

I tested the variable $user_id being passed into the method, and it is working ok, and this query works when I use the actual value of $user_id, but I get the above error message when I try to use $user_id.

It must be something simple that I’m not seeing, but I can’t figure out what it is. Any suggestions?

You need to use double quotes to enclose your string, otherwise PHP will treat $user_id as text rather than replacing it with the variable’s value.

1 Like

Of course! I knew it had to be something I should have seen, but was totally blind to. Thank you for responding so quickly!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.