首页 > 解决方案 > 如果表中存在数据,则不再保存

问题描述

在我的 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();
}

上面的代码再次将现有电子邮件保存在表中。

如何不将重复的电子邮件保存在表格中?

标签: phpwordpress

解决方案


您可以执行以下操作:

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
{
}

推荐阅读