You can improve your code a lot. I’ll treat the email address as the student’s unique identification, since I can definitely have 2 students named ‘John Doe’.
global $wpdb;
$tablename = $wpdb->prefix."students";
if(isset($_POST['submit'])){
$name = esc_attr($_POST['firstname']);
$surname = esc_attr($_POST['lastname']);
$email = sanitize_email($_POST['email']);
if(!is_email($email)) {
//Display invalid email error and exit
echo '<div class="error"><p>Invalid e-mail!</p></div>';
//return or exit
}
//Checking to see if the user email already exists
$datum = $wpdb->get_results("SELECT * FROM $tablename WHERE students_email="".$email.""");
//Print the $datum object to see how the count is stored in it.
//I'm assuming the key is 'count'
if($wpdb->num_rows > 0) {
//Display duplicate entry error message and exit
?>
<div class="wrap">
<div class="error"><p>Student exsist!</p></div> <!-- wp class error for error notices --->
</div>
<?php
//return or exit
}
//Now since the email is unique and valid, lets go ahead and enter it
//assigning the new data to the table rows
$newdata = array(
'students_name'=>$name,
'students_lastname'=>$surname,
'students_email'=>$email,
'students_date'=>current_time( 'mysql' ),
);
//inserting a record to the database
$wpdb->insert(
$tablename,
$newdata
);
//displaying the success message when student is added
?>
<div class="wrap">
<div class="updated"><p>Student added!</p></div>
</div>
<?php }
I have avoided a lot of unnecessary conditions and loops. Try this. Use some JavaScript to clear your form when a successful entry is made.
Update:
I have used get_results
in accordance with the query you had posted. Now you have to use $wpdb->num_rows
to count the number of results in the condition.
Source:
https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
https://wordpress.org/support/topic/wpdb-mysql_num_rows