Php 如果表中存在数据,请不要再次保存

Php 如果表中存在数据,请不要再次保存,php,wordpress,Php,Wordpress,在我的WordPress v5.5.3中,我有一个表单,通过以下功能,我尝试使用电子邮件密钥检查数据是否存在: // EMAIL $email = filter_input(INPUT_POST, 'email'); // TABLE global $wpdb; $tablename = $wpdb->prefix . 'new_table'; //CHECK IF EMAIL EXISTS $email_exists = "SELECT * FROM $tablename

在我的WordPress v5.5.3中,我有一个表单,通过以下功能,我尝试使用电子邮件密钥检查数据是否存在:

// EMAIL
$email = filter_input(INPUT_POST, 'email');

// TABLE
global $wpdb;
$tablename = $wpdb->prefix . 'new_table';

//CHECK IF EMAIL EXISTS
$email_exists = "SELECT * FROM $tablename WHERE form_email = $email";
$email_exists_results = $wpdb->get_results($email_exists);

// IF EMAIL DOES NOT EXISTS, REGISTER EMAIL    
if (count($email_exists_results) == 0) {
    $data = array(
        'form_email' => $email,
);
$wpdb->insert($tablename, $data);

} else {
    // IF EMAIL EXISTS, SEND MAIL
    wp_mail();
}
上述代码正在表中再次保存现有电子邮件


我如何才能不在表中保存重复的电子邮件?

您可以执行以下操作:

global $wpdb;
// get_var returns a single value 
$count = $wpdb->get_var(
// prepare takes care of parameters
// Select count() retuns a scalar value not the whole row
  $wpdb->prepare("SELECT count(*) FROM %s WHERE form_email = '%s'",
    $wpdb->prefix . 'new_table',
    filter_input(INPUT_POST, 'email')
  )
);
// Using strict comparison to avoid implicit type conversion 
if ($count === 0)
{
    // Email not in the db
}
else
{
}

您的查询很可能由于缺少$email左右的引号而失败,您应该使用参数化查询来防止SQL注入谢谢,是的,我在查询中缺少了
$email
左右的单引号。如果您能在本例中告诉我如何使用参数化查询,那就太好了。提前感谢。不使用上述代码保存数据。这是有效的
$email\u exists=“选择*FROM$tablename,其中form\u email=$email”$email_exists_results=$wpdb->get_results($email_exists);//如果电子邮件不存在,则在以下情况下注册电子邮件(计数($EMAIL\u EXISTS\u results)==0){