Use $wpdb in wordpress theme files

You need to connect your script to WordPress before you can use $wpdb.

The usual way to do this is to include wp-blog-header.php:

 include "/path/to/wordpress/wp-blog-header.php";