php - 如果表中存在数据,则不再保存
问题描述
在我的 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
{
}
推荐阅读
- jmeter - 如何在 JMeter 中运行 Robot Framework 测试用例?
- dataset - 如何在 Google 数据集搜索上发布我的数据集?
- javascript - 有没有办法从 three.js QuickHull 实例中获取顶点数组?
- r - 使用 ECDF 手动计算两样本 kolmogorov-smirnov
- r - R ranger 包中的预测概率
- angular - 在 Angular 2 项目中使用 PureMVC 框架
- java - 当我发布到 HTTP 而不是 HTTPS 时,它会调用 get 路由
- javascript - 如何获取 CSS 3D 转换画布的画布相对鼠标位置?
- octave - 为什么我在 Octave trisurf 中得到奇数 0,0 点
- angularjs - AngularJS - 带有 ng 重复的基本 $index