-2

I am trying to mod a script written for MySQL to mysqli and have been successful up to this error:

Warning: get_resource_type() expects parameter 1 to be resource, object given (etc)

Here is the code:

  function free_result($queryid=-1)
  {
    if($queryid != -1)
    {
      $this->queryid = $queryid;
    }
    if((get_resource_type($this->queryid)==='mysql result') && is_resource($this->queryid))
      return @mysql_free_result($this->queryid);
    else
    {
      return false;
    }
  }

I can't for the life of me figure out how to change this to update it to mysqli.

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

2

Unlike the old MySQL functions, MySQLi methods don't return resources. They either return an object or some other string/integer/boolean/null type. The error message is crystal clear. The function get_resource_type() expects a resource, as an argument, and you're giving it an object.

Be sure to read about Types in PHP for clarification on the differences between resource types and object types.

My guess here is that you expect $this->queryid to be a MySQLi_Result object, and that's what you're trying to check for. So rather than get_resource_type() use the instanceof operator instead, to check the object's type.

  function free_result($queryid = -1) {
    if($queryid != -1) {
      $this->queryid = $queryid;
    }
    
    if($this->queryid instanceof MySQLi_Result)
      return mysqli_free_result($this->queryid);
    } else {
      return false;
    }
  }

Alternatively, you can just Type Hint the function's prototype to only accept objects of type MySQLi_Result to simplify your code and make it easier to test.

  function free_result(MySQLi_Result $queryid = null) {
    if($queryid) {
      $this->queryid = $queryid;
    }
    
    if($this->queryid instanceof MySQLi_Result) {
        return mysqli_free_result($this->queryid);
    } else {
      return false;
    }
  }

Also, please stop using the error silence operator @. No good can ever come of that.

Make sure you're calling mysqli_free_result() and not the old mysql_free_result() function, also, as mentioned in the comments.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sherif
  • 11,786
  • 3
  • 32
  • 57
1

You need to understand that MySQli returns an object instead of a resource. So you should test for that

If($query instanceof mysqli_result)
Machavity
  • 30,841
  • 27
  • 92
  • 100