connecting to DB from custom php file

You’re must load WP-load function
To do that you need to require wp-load file, so if, your custom file is in theme it shoudl look like somethink like that:

$wp_load = '../../../../../wp-load.php';
if ( file_exists( $wp_load ) ) {
    require_once( $wp_load );
}else{
    die('no-load');
}

You could also set const SHORTINIT to true to minimalize WP loads… it’s helpfull if you dont need full WP crap etc, butw you can load WP elements … depend of your needs

function wp_load_utils ( ) {
   require( ABSPATH . WPINC . '/class-wp-walker.php' );
   require( ABSPATH . WPINC . '/l10n.php' );
   require( ABSPATH . 'wp-admin/includes/admin.php' );
   require( ABSPATH . WPINC . '/formatting.php' );
   require( ABSPATH . WPINC . '/pluggable.php' );
   require( ABSPATH . WPINC . '/script-loader.php' );
   require( ABSPATH . WPINC . '/general-template.php' );
   require( ABSPATH . WPINC . '/link-template.php' );
   //require( ABSPATH . WPINC . '/shortcodes.php' );
   wp_functionality_constants();
}

function wp_load_session ( ) {
   require( ABSPATH . WPINC . '/capabilities.php' );
   require( ABSPATH . WPINC . '/user.php' );
   require( ABSPATH . WPINC . '/meta.php' );
   require( ABSPATH . WPINC . '/post.php');
   require( ABSPATH . WPINC . '/class-wp-user.php' );
   require( ABSPATH . WPINC . '/class-wp-roles.php' );
   require( ABSPATH . WPINC . '/class-wp-role.php' );
   require( ABSPATH . WPINC . '/session.php' );
   wp_cookie_constants();
}

Below my custom ajax file that handle Ajax request instead of admin-ajax.php, it is much faster … like standard need about 200-400ms to hit admin.php output, this using only shortint is able to do it under 50ms

https://gist.github.com/isuke01/a4d22fc19240928597a0dfed1af791e8