What fobos said. Your programs are doing exactly what you programmed them to do. You are intermixing unrelated and otherwise unconnected execution environments; I still screw it up now and again after years of programming PHP, HTML and JS. Examine the HTML/JS on your browser; That's what runs on your browser, not your PHP program.
Think of PHP as a program generator. That is, it generates a static program (HTML/JS) that is sent to the browser to be executed. After the server has shipped the program to the browser, the server PHP program is done and no longer running. You have to generate your HTML/JS such that it has all the information it needs.
Next, by the time the PHP generates your getrating() function, $row is null--it must be, in order to exit the while loop above. So eliminate the loopy-loop complexity. Drop the ID and value and move the $row[] arg from getElementById to each and every getrating() function call. Tweak your code to be straightforward. You already know the row ID when you are generating the tags, so call getrating() with the ID arg pre-set.
A simple task flow:Write a PHP program to generate an HTML/JS program.
Verify that the PHP program is correct.
If the generated HTML/JS is incorrect, reprogram your PHP code and go to step 2.
That is, keep writing and re-writing your PHP code until the generated HTML/JS is correct. Remember: you aren't just writing a program; you are writing a program that writes a program. Keep that extra level of abstraction in mind at all times.