php – Can’t send form data to wpdb when URL has query string

Question

I see a few issues with the code:

First, the form action is not set correctly. It should be something like:

<form action="<?php echo esc_url( get_the_permalink() ); ?>" method="post">

In the PHP code, you are using the wrong table name. You are using the table name ‘invites’ instead of ‘rsvp’. You should change this line:

$rsvp_table = $wpdb->prefix . 'invites';

to:

$rsvp_table = $wpdb->prefix . 'rsvp';

You need to sanitize the form input data before inserting it into the database. You should use the sanitize_text_field() function to sanitize the input data. For example:

$name = sanitize_text_field( $_POST['name']);

You should check for errors after inserting data into the database, and display an error message if there are any errors. You can do this by adding this code after the call to $wpdb->insert():

if ( $wpdb->last_error !== '' ) {
    // There was an error
    echo $wpdb->last_error;
} else {
    // Success
    echo 'Data was inserted successfully';
}

You should also consider nonce verification for security purposes. You can add a nonce field to the form and verify it before inserting data into the database. For example:

<input type="hidden" name="my_form_nonce" value="<?php echo wp_create_nonce( 'my_form_nonce' ); ?>" />

And then in the PHP code, you can verify the nonce like this:

if ( ! wp_verify_nonce( $_POST['my_form_nonce'], 'my_form_nonce' ) ) {
    // Nonce verification failed, do not insert data
    return;
}

With these changes, your code should work as expected.

0
Freddy 2 months 2022-12-04T16:01:19-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse