如何在一些预先检查后将值插入db

时间:2015-11-05 22:05:12

标签: php mysql

我想在数据库中插入一些值,但在插入之前我想确保同一用户对同一offernamecurrent date

没有重复的条目

我正在使用此查询,并且可以正常使用useriddate

//checking for existing values
$sql11=$Db1->query("SELECT COUNT(userid) AS total FROM TABLE where userid='$userid' and date BETWEEN (NOW() - INTERVAL 1 DAY) AND NOW()");
        $temp=$Db1->fetch_array($sql11);
         $thismemberinfo['count']=$temp[total]; 
    //   
       if ($thismemberinfo['count'] >= 1 ) 
        {  WARN HERE  for duplicate entry}
        else 
        { INSERT TO DB }

我也希望将offername纳入检查范围 类似的东西

SELECT COUNT(userid) AS total FROM TABLE where userid='$userid' and  offername= '$offername'  date BETWEEN (NOW() - INTERVAL 1 DAY) AND NOW() 

请建议解决此问题

1 个答案:

答案 0 :(得分:0)

  

注意:

     

您不应将表名用作 TABLE 和列名 date ,因为这两个字是保留字在查询中。使用其他名称。

     

为了使您的查询更简单,只需在添加之前检查列(user_id和amp; date)。

请参阅我的代码,了解我的工作方式。

//checking for existing values
$sql11=$Db1->query("SELECT COUNT(userid) AS total FROM TABLE where userid='$userid' AND offername= '$offername' AND  date BETWEEN (NOW() - INTERVAL 1 DAY) AND NOW()");
$temp = $Db1->fetch_array($sql11);
$thismemberinfo['count']=$temp['total'];  
if ($thismemberinfo['count'] >= 1) {
    // Just do nothing 
} else {
    //INSERT TO DB 
    //Current date
    $current_date = date('Y-m-d');

    $Db1->query("INSERT INTO TABLE (userid,offername,date) VALUES ('$user_id','$offername','$current_date')");
    //Table should be replace with suitable name since TABLE is a reserved word in query
}