Moved $query declaration to the point after $friendID is defined. The query was passing null for friendID before, since it was defined before friendID was updated with a correct value.