0

I am trying to use table data in a single row data as the value of an variable in my code below and i keep getting "Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\done\test1.php on line 29"

    // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT lev1   FROM ref where id=1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "lev1: " . $row["lev1"]. "";
  }
} 



$mamo=$row["lev1"];
$conn->close();

what I'm I dong wrong ?

Ian Kioko
  • 1
  • 1
  • 1
    _“what I'm I dong wrong ?”_ - did the error message not just tell you that? `$row` is not an array, but only contains NULL. It appears you don’t actually think about the code that you are using, resp. did not bother to figure out who it works in the first place? The while loop over the result set ends, _because_ `fetch_assoc` will return NULL, after the last available record was processed in the previous iteration. So you can not access any data via $row now _after_ the loop any more. – CBroe Feb 24 '21 at 13:58
  • I assume line 29 is `$mamo=$row["lev1"];`. Read the "Return value" section of the `fetch_assoc` [manual](https://www.php.net/manual/en/mysqli-result.fetch-assoc). – El_Vanja Feb 24 '21 at 14:00
  • Also assuming `id` is the PK thus unique, a loop is totally useless... – the_nuts Feb 24 '21 at 14:03

1 Answers1

0

Trying to access array offset on value of type null

It means that $row is null (in the $mamo=$row["lev1"]; line), therefore it cannot behave as an array.

If you're using while ($row = $result->fetch_assoc()), it will keep assigning values to $row until it can no more (because that's supposed to break the loop). After you reach the last result, $row will always inevitably be null.