Please dont paste the entire code for your page into the message body. Instead, you should add the original PHP page into a zip archive and attach the zip archive to your message.
The code to set the session variable is before the code that creates the recordset.
You are setting the session variable near the top of message 5. The recordset does not get created until around the middle of the code in message 7. The session variable cannot get the value form a recordset that has not been created yet.