Use admin-post to submit form data to external database

I’m answering this question to help future WordPress developers on their quest for knowledge. The answer is YES, you can connect to an external database when using the admin_post action. Below is the corrected source…

<?php
class x94 {

    private $externalDB01;

    public function __construct(){
        add_action( 'admin_post_submitForm9', array( $this, 'formHandling' ), 11, 1 );
        add_action( 'plugins_loaded', array( $this, 'externalDB' ), 10, 1 );
    }

    //External DB connection
    function externalDB(){ 
        $this->externalDB01 = new wpdb(DB_USER2, DB_PASSWORD2, DB_NAME3, DB_HOST2);
    }

    //create form
    function userForm() {

        ob_start(); 
        ?>
        <form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post" id="test" >

            <input type="hidden" name="action" id="userForm_action" value="submitForm9" />
            <input type="text" name="visitor_name" id="visitor_name" /> 
            <input type="text" name="visitor_age" id="visitor_age" /> 
            <input type="text" name="visitor_gender" id="visitor_gender" /> 

            <input type="submit" name="submit_form" value="submit" />

        </form>
        <?php
        $html = ob_get_clean();
        return $html;

    }

    function formHandling(){

        if ( isset( $_POST) ) { 

            //sanatize data from the admin-post array
            $name   = sanitize_text_field( $_POST['vistor_name'] );
            $age    = sanitize_text_field( $_POST['vistor_age'] );
            $gender = sanitize_text_field( $_POST['vistor_gender'] );

            //submit data to external database
            $externalDB->insert( 
                'basic_user_info', 
                array( 
                    'name' => $name, 
                    'age'  => $age,
                    'gender'=> $gender,

                ),
                //field formats
                array('%s',
                      '%s',
                      '%s',
                      )
            );
        }
        else {

            wp_die();
        }
    }
}//end class

//shortcodes
add_shortcode('basic-info', array( 'x94', 'userForm' ) );


new x94();
?>