如何使用WHERE NOT EXISTS查询来避免使用$wpdb保存在定制表中的重复条目?

时间:2017-09-12 作者:dilip shrestha

我是worpress数据库的新手,一直在检查用户电子邮件的重复条目。我想在$wpdb中转换以下sql查询

  $sql = "INSERT INTO trip_rate (id, trip, rating, r_name, email, title, review) 
  SELECT  \'\', \'$trip\', \'$rating\', \'$name\', \'$email\', \'$title\', \'$review\' 
  WHERE NOT EXISTS (
  SELECT email FROM trip_rate WHERE email=\'$email\' AND trip=\'$trip\')";


if(mysql_affected_rows() > 0){
    echo \'Review saved\';
}
else{
    echo \'You have already reviewed this trip!\';
}
将其转换为WordPress的新代码

 <?php
if( isset($_POST[\'submit\']) ) {
$trip = $_POST[\'trip\'];
$rating = $_POST[\'rating\'];
$name = $_POST[\'name\'];
$email = $_POST[\'email\'];
$title = $_POST[\'title\'];
$review = $_POST[\'review\'];

global $wpdb;
$wpdb->dmtable = $wpdb->base_prefix . \'trip_rate\';
$my_part_ID = (bool)$wpdb->get_var(
    $wpdb->prepare(
        "SELECT COUNT(r_email) FROM {$wpdb->dmtable}
                WHERE r_email = %d AND trip = %d LIMIT 1",
        $email, $trip
    )
);

if ($my_part_ID){
    echo"already reviewed";
}
else{
    global $wpdb;
    $wpdb->insert(\'sb_trip_rate\',array(\'trip\'=>$trip, \'rating\'=>$rating, \'r_name\'=>$name,\'r_email\'=>$email, \'title\'=>$title, \'review\'=>$review,),array(\'%s\', \'%s\', \'%s\', \'%s\',\'%s\',\'%s\'));
    }

}
?>
尽管电子邮件字段是唯一的,但它仍会将值保存到表中

1 个回复
SO网友:Annapurna

哪里不在你需要的。

$sql=“插入trip\\u rate(id、trip、rating、r\\u name、email、title、review)选择“”、“$trip”、“$rating”、“$name”、“$email”、“$title”、“$review”,其中(trip\\u rate.email)不在(从trip\\u rate中选择电子邮件,其中电子邮件=“$email”和trip=“$trip”)”;

结束