WordPress form into database

I am writing a plugin and among other things it should insert info from a form into a database. When I put some data into the form, though, there is nothing inserted into the database. Here is my code:

function ol_process_shortcode(){
        return '<form method="post"><p><label for="name">Jméno:</label><input type="text" name="ol-name" id="name" /></p><p><label for="email">Email:</label><input type="text" name="ol-email" id="email" /></p><p><input type="submit" name="ol-odeslat" value="Odeslat" /></p></form>';
        if ( isset( $_POST['ol-odeslat'] ) ) {
            $name    = sanitize_text_field( $_POST["ol-name"] );
            $email   = sanitize_email( $_POST["ol-email"] );
            require_once('../../../wp-config.php');
            global $wpdb;
            $table_name = $wpdb->prefix . "xxx";
            $wpdb->insert( $table_name, array( "Name" => $_POST["ol-name"], "Email" => $_POST["ol-email"] ) );
        }
}

What am I doing wrong? Also is it validated properly? I am not sure what should the “Name” and “Email” refer to on the last line.

Related posts

1 comment

  1. The return needs to go last. If you have it first, the code after will never get executed.

    function ol_process_shortcode(){
        if ( isset( $_POST['ol-odeslat'] ) ) {
            $name    = sanitize_text_field( $_POST["ol-name"] );
            $email   = sanitize_email( $_POST["ol-email"] );
            global $wpdb;
            $table_name = $wpdb->prefix . "xxx";
            $wpdb->insert( $table_name, array( "Name" => $_POST["ol-name"], "Email" => $_POST["ol-email"] ) );
        }
        return '<form method="post"><p><label for="name">Jméno:</label><input type="text" name="ol-name" id="name" /></p><p><label for="email">Email:</label><input type="text" name="ol-email" id="email" /></p><p><input type="submit" name="ol-odeslat" value="Odeslat" /></p></form>';
    }
    

    …also removed the inclusion of wp-config.php since it’s already loaded by WordPress.

Comments are closed.