just for the test, use this method:
$result=mysql_query($qry) or die("query error: ". mysql_error());
Then you will see what is the problem with that query, a table name, a field name might be the mistake.
Before you run a query in php, try it in phpmyadmin.
in your code $userid looks like an undefined index!
but!
if i were your visitor, i will quess the sitenames.
After i hit the right pin codes,
set to me a SESSION variable with that site ID!
Then check on evry pages, that site ID (that value comes from the databse) has enabled in the visitor's session. If not, header location back !