0

I seem to be receiving a number of php notices advising 'Trying to get property of non-object'.

I assume it is the way I have structured the mysql statement but I am a little unsure and I am after assistance here.

The function is as follows:-

public function getPreviousBlock($iHeight=0) {
    $stmt = $this->mysqli->prepare("
        SELECT height
        FROM " . $this->block->getTableName() . "
        WHERE height < ?
        ORDER BY height DESC
        LIMIT 1");
    if ($this->checkStmt($stmt) && $stmt->bind_param('i', $iHeight) && $stmt->execute() && $result = $stmt->get_result())
        return $result->fetch_object()->height;
    return $this->sqlError();
}

Any help would be much appreciated.

user4020527
  • 1
  • 8
  • 20
daygle
  • 61
  • 7

1 Answers1

1

fetch_object() will return NULL if there are no more rows in the result set. Of course NULL is not an object so you will get this error.

So you need to check for example:

$obj = $result->fetch_object();
if ($obj) {
   return $obj->height;
} else {
   return null;
}
Vũ Nhật Anh
  • 512
  • 5
  • 14
  • Thanks for the help :) – daygle Jan 11 '18 at 05:02
  • Does this look correct?`public function getPreviousBlock($iHeight=0) { $stmt = $this->mysqli->prepare(" SELECT height FROM " . $this->block->getTableName() . " WHERE height < ? ORDER BY height DESC LIMIT 1"); if ($this->checkStmt($stmt) && $stmt->bind_param('i', $iHeight) && $stmt->execute() && $result = $stmt->get_result()) $obj = $result->fetch_object(); if ($obj) { return $obj->height; } else { return null; } return $this->sqlError(); }` – daygle Jan 11 '18 at 05:06
  • I think it should be like this ```function getPreviousBlock($iHeight = 0) { $stmt = $this->mysqli->prepare(" SELECT height FROM " . $this->block->getTableName() . " WHERE height < ? ORDER BY height DESC LIMIT 1"); if ($this->checkStmt($stmt) && $stmt->bind_param('i', $iHeight) && $stmt->execute() && $result = $stmt->get_result()) { $obj = $result->fetch_object(); if ($obj) { return $obj->height; } else { return null; } } return $this->sqlError(); } ``` – Vũ Nhật Anh Jan 11 '18 at 06:39