[FIXED] Trying to access array offset on value of type null for array populated from MySQLi result set

Issue

I finally got round to updating my PHP install to 7.4 from 7.2 (Planning on going right to current but doing in steps) and a curious error appeared when I was running an existing script:

Message: Trying to access array offset on value of type null

The line that this appears on is simply to populate an array from a simple mysql result set.

for($i = 0; $resultArray[$i] = mysqli_fetch_row($result)[0]; $i++) ;

The script still continues fine but I just don't like any errors. I'm scratching my head why this has errored and searched for a few hours to no avail. Why is this erroring and is there a way to do the same thing with no error?


Solution

mysqli_fetch_row will return null at some point (as it always does when it runs out of rows to retrieve, as per the documentation). But you're not checking that before trying to read its 0th index, hence the error.

Many people retrieve rows using this kind of style:

while ($row = mysqli_fetch_row($result)) { 
  $resultArray[] = $row[0]; 
}

which will avoid this sort of problem. That's the way you'll often see it done in examples and documentation, too.



Answered By - ADyson
Answer Checked By - Timothy Miller (sql.easybugfix Admin)

Related Posts

Post a Comment