Search code examples
phpclassmethodsprepare

Call to a non-object workaround?


I have a method like this:

public function query ($sql) {
  $this->result = $this->db->query($sql);
}

Binds the query statement to the result variable. This is really handy because I have several methods that output something and another method that then handles the $result variable for other tasks.

However I wanted to use the same kind of method, but on prepared statements(to escape data that gets inserted) and I ran into a problem:

public function prepare ($sql) {
  $this->result = $this->db->prepare($sql);
}

I tried to use it like this:

public function insert ($this, $that) {
  // Then I tried to use my prepare method
  $var = $this->prepare(INSERT INTO Table (Row1, Row2) VALUES (:Val1, :Val2));
  $var->bindValue(":Val1", $this, PDO::PARAM_INT);
  //... and so on
}

The problem shows up on the $var->bindValue() "Call to a member function bindvalue() on a non-object". What is exactly happening here because I don't really understand the error message? If I query my db using the query method it works just fine, but how can I bind values using the prepare method?


Solution

  • In:

    public function ($sql) {
      $this->result = $this->db->prepare($sql);
    }
    

    You forget to return the result. (You also forgot the name of the function in the snippet.)

    The error message is quite clear, you're calling a method on something that's not an object. In this case you're calling it on NULL because your own prepare-method doesn't return anything.