admin管理员组

文章数量:1122846

I am creating a custom form in WordPress to store and send data to an external database. As part of testing, I was successful in creating a form that submitted form data to the external database by having the form refer back to itself upon clicking the submit button.

I now would like to leverage WordPress admin-post functionality instead of having the form refer back to itself. I have set up the action hook correctly as I see the $_POST variables displayed once the form is submitted using:

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

My question, can an external database be used with admin-post? At this point, when referencing the global variable for the external database connection, a PHP error is thrown stating that insert is referring to a NULL value. Below is relevant code pertaining to the issue...

<?php
class x94 {

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

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

    //create form
    function userForm() {
    //Global Variables

        global $externalDB;
        //print_r($externalDB);

        // starts output buffering
        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();

        if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] != "" ) {
            //$_POST Variables
            $name = strip_tags($_POST["visitor_name"], "");
            $age = $_POST['visitor_age'];  
            $gender = $_POST['visitor_gender']; 



        }
        // if the form is submitted but the name is empty
        if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] == "" )
            $html .= "<p>You need to fill the required fields.</p>";
        // outputs everything
        return $html;

    }

    function formHandling(){

        global $externalDB;
        print_r($externalDB); //not displaying data, global not recognized
        print_r($_POST); //displays data

        if (1 == 1){

            $externalDB->insert( 
                'basic_user_info', 
                array( 
                    'name' => $name, 
                    'age'  => $age,
                    'gender'=> $gender,

                ),
                //field formats
                array('%s',
                      '%s',
                      '%s',
                      )
            );
            //$html = "<p>Your name <strong>$name</strong> was successfully recorded. Thanks!!</p>";
            die();
        }
    }
}//end class

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


new x94();
?>

I am creating a custom form in WordPress to store and send data to an external database. As part of testing, I was successful in creating a form that submitted form data to the external database by having the form refer back to itself upon clicking the submit button.

I now would like to leverage WordPress admin-post functionality instead of having the form refer back to itself. I have set up the action hook correctly as I see the $_POST variables displayed once the form is submitted using:

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

My question, can an external database be used with admin-post? At this point, when referencing the global variable for the external database connection, a PHP error is thrown stating that insert is referring to a NULL value. Below is relevant code pertaining to the issue...

<?php
class x94 {

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

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

    //create form
    function userForm() {
    //Global Variables

        global $externalDB;
        //print_r($externalDB);

        // starts output buffering
        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();

        if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] != "" ) {
            //$_POST Variables
            $name = strip_tags($_POST["visitor_name"], "");
            $age = $_POST['visitor_age'];  
            $gender = $_POST['visitor_gender']; 



        }
        // if the form is submitted but the name is empty
        if ( isset( $_POST["submit_form"] ) && $_POST["visitor_name"] == "" )
            $html .= "<p>You need to fill the required fields.</p>";
        // outputs everything
        return $html;

    }

    function formHandling(){

        global $externalDB;
        print_r($externalDB); //not displaying data, global not recognized
        print_r($_POST); //displays data

        if (1 == 1){

            $externalDB->insert( 
                'basic_user_info', 
                array( 
                    'name' => $name, 
                    'age'  => $age,
                    'gender'=> $gender,

                ),
                //field formats
                array('%s',
                      '%s',
                      '%s',
                      )
            );
            //$html = "<p>Your name <strong>$name</strong> was successfully recorded. Thanks!!</p>";
            die();
        }
    }
}//end class

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


new x94();
?>
Share Improve this question asked Jul 29, 2018 at 8:04 29A29A 1114 bronze badges 5
  • add_action( 'wp_head', array( $this, 'externalDB' ), 10, 1 ); - how about replace that with $this->externalDB();? Or if you want to wait for plugins to be loaded, replace wp_head with plugins_loaded. – Sally CJ Commented Jul 29, 2018 at 8:29
  • And because the database connection is initiated from the x94 class, why not store the wpdb instance (which is currently the global $externalDB variable) in a property of the class? Like this: add private $db; then in the externalDB() function, use $this->db = new wpdb(DB_USER2, DB_PASSWORD2, DB_NAME3, DB_HOST2);, then remove the global $externalDB; and change the $externalDB to $this->db. (And rename externalDB() to db()..) – Sally CJ Commented Jul 29, 2018 at 8:39
  • 1 @Sally CJ - thank you for the suggestions, I will begin to work through these and let you know what I come up with. – 29A Commented Jul 30, 2018 at 1:21
  • 1 @Sally CJ - Thank you for the tip to use the plugins_loaded for the add_action, I successfully viewed the variables for the external database on the admin-post.php page ;) Also followed your suggestions for using the $externalDB variable and changing it to a property in the class. Was able to access the external database once I cleaned up some source for the if statement. Will post full solution for future readers. – 29A Commented Jul 30, 2018 at 5:09
  • I'm glad you got it sorted. All the best. =) – Sally CJ Commented Jul 30, 2018 at 5:59
Add a comment  | 

1 Answer 1

Reset to default 0

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();
?>

本文标签: plugin developmentUse adminpost to submit form data to external database