You've run afoul of PHP's vicious anti-global variable design. It's actually a good thing that will teach you to program well, but a pain for beginners.
Basically, in PHP, global variables don't exist within functions by default. Since $dbname1 is not assigned in the function, the function can't see it. To "suck it in" to the function (not recommended) use the global keyword like so:
function myfunc ($var1, $var2){
global $dbname;
(rest of function goes here)
}
Or you can pass it in as an argument:
function myfunc($var1, $var2, $dbname){
which is how I recommend doing it.