1

I'm trying to populate a group of textboxes with data queried from a database.

The php for loop runs 4 times, evidenced by 4 names in the pulldown. However, only the first two pulldown options work (populating the text boxes, not shown here)

echo "<script> var students = [[],[]];";
$students = "";
for($i=0; $i<$query->rowCount(); $i++) {
    echo "students[$i][0] = " . $result[$i]['studentID'] . ";";
    echo "students[$i][1] = " . $result[$i]['coachID'] . ";";
    echo "students[$i][2] = " . $result[$i]['schoolID'] . ";";
    echo "students[$i][3] = '" . $result[$i]['firstName'] . "';";
    echo "students[$i][4] = '" . $result[$i]['lastName'] . "';";
    echo "students[$i][5] = " . $result[$i]['grade'] . ";";
    $students .= "<option value='$i'>" . $result[$i]['firstName'] ."</option>";
}
echo "</script>";

Chrome's debugger throws an error on page load, "Uncaught TypeError: Cannot set property '0' of undefined" referencing the line of php-generated code, "students[2][0] = 56784"

I put the message in Google, and found this page which confirms (I think?) that the for loop is only filling students[][] with 2 of the 4 records.

I can't figure out why it works just fine for the first two and not for the other two. Please tell me this isn't a simple syntax error.

Community
  • 1
  • 1
donutguy640
  • 377
  • 1
  • 4
  • 20

1 Answers1

1
var students = [[],[]];

students is an array with 2 elements. Accessing the 3rd element (students[2]) yields undefined. students[2][0] is undefined[0], which is an error.

To fix it, you need to initialize students with $query->rowCount() elements, not just 2.

Alternatively, add

echo "students[$i] = [];";

at the beginning of your loop.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • Hmm, I could have sworn I read somewhere that arrayName[[],[]] was a 2 dimensional array...That fixed it though, thank you very much! – donutguy640 Jun 25 '16 at 01:18