too long

I've got a loop posting images from database. I tried to give each photo div separate id. When i tried to send it to script by onclick function It shows that "$photoid is not defined " I tried to print this variable in this first php script but it shows me all IDs, so shouldnt be empty or undefined...

$allphotos = mysql_query("SELECT * FROM photos ORDER BY id DESC");

while ($numphotos = mysql_fetch_assoc($allphotos)){

$photoinfo = mysql_query('SELECT * FROM photos WHERE link="'.$numphotos['link'].'" ');
$fetchinfo = mysql_fetch_assoc($photoinfo);

$photoid = $fetchinfo['id']; 
echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" onclick=clicked($photoid)></div>';
}

Here goes script:

  <script>
    function clicked(photoid){
    document.getElementById('photoid').style.backgroundColor = 'red'
    }
    </script>

Change this:

echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" onclick=clicked($photoid)></div>';

to this:

echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" onclick="clicked('.$photoid.');"></div>';

otherwise, the output is just clicked($photoid), all text.

Also change that:

function clicked(photoid){
document.getElementById('photoid').style.backgroundColor = 'red'
}

to that:

function clicked(photoid){
document.getElementById( photoid.toString() ).style.backgroundColor = 'red';
}

This is simply an escaping issue. The argument $photoid in your echoed function has to be escaped if it is a string. In your code above this:

onclick=clicked($photoid)

should be

onclick="clicked($photoid)"

if $photoid is a number or

onclick="clicked(\'$photoid\')"

if it is alphanumeric or a string

The answer above is working, but they forgot to add something,

instead of

echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" onclick="clicked('.$photoid.');"></div>';

copy this code

echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" style="background-color:white" onclick="clicked('.$photoid.');"></div>';

add the style="background-color:white;" i think you can't access the .style in js if you didn't initialize it in your div. hope this will help