-2

So I have this code that takes data from a database and I want to just list them out, but it adds another thing to the array "[3] =>" even though I only have 3 things in my database (it starts counting from 0). But because [3] is empty it gives me my expected output ("user1user2user3") and then it gives me the error message "Trying to access array offset on the value of type null". How do I get rid of this message or stop it from adding [3]? This is my code:

$fetch_data = mysqli_query($conn, "select username, email from login");
while($check_data[] = mysqli_fetch_array($fetch_data));

print_r($check_data);

$id_check_username = 0;
foreach($check_data as $id_check_username => $username){
    echo $check_data[$id_check_username][0]; /*this is line 48*/
};

This is my output:

Array ( [0] => Array ( [0] => user1 [username] => user1 [1] => email1 [email] => email1 ) [1] => Array ( [0] => user2 [username] => user2 [1] => email2 [email] => email2 ) [2] => Array ( [0] => user3 [username] => user3 [1] => email3 [email] => email3 ) [3] => ) user1user2user3

Warning: Trying to access array offset on the value of type null on line 48

What does it mean?

s123
  • 102
  • 9

1 Answers1

0

Obviously $check_data[3] is empty, the way you used to fetch the results is a bad practise. If you want to fetch all rows, use mysqli_fetch_all.

$check_data = mysqli_fetch_all($fetch_data);

If you prefer to fetch rows one by one, you'd better fetch a row first, assign it to the array next.

while($row = mysqli_fetch_array($fetch_data))
    $check_data[] = $row;

In addition, in the code $username already contains row data, the loop could be simplified to:

foreach($check_data as $username)
    echo $username[0];
shingo
  • 18,436
  • 5
  • 23
  • 42