Saving custom form data into database

OK, so here is how you should to this proper way…

In your template file you put your form:

<form id="myForm" name="myform" action="<?php echo esc_attr( admin_url('admin-post.php') ); ?>" method="POST">
    <input type="hidden" name="action" value="save_my_custom_form" />
    <select id="brandSel" size="1">
        <option selected="selected" value="">-- Select Brand --</option>
        <option>Abba</option>
        <option>AG Hair</option>
    </select>

    <input type="submit" value="submit" />
</form>

And in functions.php file (or in your plugin) you’ll have to add admin_post_{action}:

function my_save_custom_form() {
    global $wpdb;

    $inputValue = $_POST['newValue'];
    $wpdb->insert(
        'catalog',
        array( 'brandSel' => $inputValue ),
        array( '%s' ),
    );

    wp_redirect( site_url("https://wordpress.stackexchange.com/") ); // <-- here goes address of site that user should be redirected after submitting that form
    die;
}

add_action( 'admin_post_nopriv_save_my_custom_form', 'my_save_custom_form' );
add_action( 'admin_post_save_my_custom_form', 'my_save_custom_form' );

Leave a Comment

tech