when I fetch data from remote mysql database in wordpress built in wordpress function is not working?

The WordPress APIs rely on the global $wpdb object, you can define any arbitrary object of type wpdb but that doesn’t mean WordPress will use it.

Instead, something akin to the following might be better:

global $wpdb;
$tempDB = $wpdb;
$wpdb = new wpdb(DB_USER2, DB_PASSWORD2, DB_NAME2, DB_HOST2);
// do your remote SQL stuff

// perhaps a WP_Query loop here?

// we're done, now restore the default and cleanup
$wpdb = $tempDB;

I would advise though that there’s very, very few instances were connecting to a second DB with a WordPress install is the optimum thing to do, there are many, many better ways of doing things. Multisite or RSS feed aggregation would probably be a lot better for you.

error code: 523