Error handling for wpdb error – displaying an error message to the user

I want to display an error message to a user when a php POST form fails. The form lets a user create a new team on my site. If the team name is not unique, the query fails. I want to display a generic error message when this happens.

Here is my form:

<form method=”post” id=”create_team” action=””>
<p class=”form”>
<label for=”team_name”><?php _e(‘Team Name:’, ‘profile’); ?></label>
<input class=”text-input” name=”team_name” type=”text” id=”team_name” value=”<?php the_author_meta( ‘team_name’, $current_user->ID ); ?>” />
</p>

<p class=”form”>
<select name=”team_type” id=”team_type” class=”styled-select”>
<option value=”” selected disabled >Team Type</option>
<option value=”School”>School</option>
<option value=”Neighborhood”>Neighborhood</option>
<option value=”Organization”>Organization</option>
</select>
</p>
<p class=”form-submit” id=”create-team-submit”>
<input name=”create_team” type=”submit” id=”create_team” class=”submit button” value= “submit” />
</p>
</form>

Here is the handler in functions.php:

function mytheme_insert_new_team() {

$name = $_POST[‘team_name’];
$type = $_POST[‘team_type’];
global $wpdb;
$table_name = “wp_teams”;

$wpdb->insert($table_name, array(
‘team_name’ => $name,
‘team_type’ => $type
),array(
‘%s’,
‘%s’)
);
if(!$response){
if($wpdb->last_error !== ”){
mytheme_print_error();
}
}else{
mytheme_redirect();
}
}

And here is my function to show the error, also in functions.php:

function mytheme_print_error(){
//append the error message after the form
echo “<script>

var error = document.createElement(‘div’);
error.class = ‘error’;
error.value = ‘There was an error. Please try again’;
var element = document.getElementById(‘create-team-submit’);
element.appendChild(error);

</script>”;
}

I get the following error:

Uncaught TypeError: Cannot read property ‘appendChild’ of null

I have double checked for typos but I can’t seem to fix it. Any advice?

Read more here:: Error handling for wpdb error – displaying an error message to the user

Leave a Reply

Your email address will not be published. Required fields are marked *