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 ?

3
  • 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. Commented Feb 24, 2021 at 13:58
  • I assume line 29 is $mamo=$row["lev1"];. Read the "Return value" section of the fetch_assoc manual. Commented Feb 24, 2021 at 14:00
  • Also assuming id is the PK thus unique, a loop is totally useless... Commented Feb 24, 2021 at 14:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you that did it :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.