There’s a lot wrong with your code:
- In your query you’re setting
reg_user_id
to$user
, when it looks like you meant to use$reg_user_id
, which is probably a problem because you’re setting$user
to$current_user->ID
even though$current_user
doesn’t exist. $_POST['reg_id']
doesn’t exist in your form, and I have no idea what you’re trying to do with$_POST['$user']
and$_POST['$time']
.- You shouldn’t escape values when using
$wpdb->insert()
. - You’re inserting with
$wpdb
, but trying to run a query from$conn
by passing it$sql
even though$wpdb->insert()
does not return SQL.
Here is code that performs the same function without those issues:
function wpse_283721_handle_form() {
global $wpdb;
if ( empty( $_POST['submit'] ) ) {
return;
}
if ( ! is_user_logged_in() ) {
return;
}
$current_user = wp_get_current_user();
$fiske_vægt = trim( $_POST['fiske_vægt'] );
$fiske_længde = trim( $_POST['fiske_længde'] );
$wpdb->insert(
$wpdb->prefix . 'registreringer',
array(
'dato' => new DateTime( 'now' ),
'fiske_vægt' => apply_filters( 'pre_register_fiske_vægt', $fiske_vægt ),
'fiske_længde' => apply_filters( 'pre_register_fiske_længde', $fiske_længde ),
'reg_user_id' => $current_user->ID,
)
);
}
add_action( 'init', 'wpse_283721_handle_form' );
Take note of the following:
- I put the function for handling the form in a hook, not in a template. It’s not clear from your code how you’ve done it, but this would be the correct way.
- Since you use the current user’s ID in the code, I do not proceed with processing the form if a user is not logged in.
- I make sure to get the current user with
wp_get_current_user()
. - I do not use
$wpdb->escape()
, for two reasons: Firstly, it has been deprecated and shouldn’t be used, and secondly,$wpdb->insert()
will do the escaping for you. - I didn’t use the date submitted with the form since the server can just set the date when inserting. If you change your table to set the default value of the
dato
column to the current time you don’t even need to do that. - I used
$wpdb->prefix
to ensure the correct table name. This is also something to do when the table is created if you’re doing that in code.
But there’s still things you’ll probably want to look into:
- Use something more secure or unique than
$_POST['submit']
to see if your form is submitted. Possibly even a nonce. - More validation or sanitisation. Like making sure all fields are present, and ensuring they are the expected types of values eg. numbers are numbers.