您可以大大改进代码。我会将电子邮件地址视为学生的唯一标识,因为我肯定可以有两个名为“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 }
我避免了许多不必要的条件和循环。试试这个。当成功输入时,使用一些JavaScript清除表单。
更新:我使用了get_results
根据您发布的查询。现在你必须使用$wpdb->num_rows
计算条件中的结果数。
资料来源:https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Resultshttps://wordpress.org/support/topic/wpdb-mysql_num_rows