I suspect that it is something to do with this line
$Userid = session_id() ;
or the way that the variable is called in this line
$add = "INSERT INTO MyTable (Userid,imageid) values ('$Userid','$that')" ;
because, when I change $Userid to equal 1, it works fine. So it has something to do with the way that sessions are being handled...but I am not sure what. Also, it carried on with this intermittent behaviour until I removed sessions and cookies from the equation altogether.