How is $db defined in the file? It is used in many places
Look at the include/require statements in front of the code to see if they are defined in the included external file
Look at the include/require statements in front of the code to see if they are defined in the included external file