2

我试图做一个 mysql 检查 $uid 中的记录是否基于 $timestamp 从今天开始存在,如果它不存在则执行 INSERT。

//EXAMPLE RECORD FROM TABLE VOTE
--- #vote_fb_uid# --- #vote_time#
     665414807        1369219044

tjt

//STEP 1 - do a look up on $uid and check with timestamp $today

        $timestamp = $this->time;
        $date = date('Y-m-d', $timestamp);
        $today = date('Y-m-d');

        $sql = "
        SELECT * FROM vote WHERE
        vote_fb_uid = '$this->fb_uid',
        WHERE vote_time = '$CHECK_IF_THERE_IS_AN_ENTRY_FROM_TODAY'";

        $res = mysql_query($sql) or die( mysql_error());

//STEP 2 - If no records are found for today - then we do an INSERT

        if($no_record_for_today) {
            $sql = sprintf("
            INSERT INTO vote(
            vote_fb_uid,
            vote_time)
            VALUES ('%s','%s')",
            mysql_real_escape_string($this->fb_uid),
            mysql_real_escape_string($this->time));

            $res = mysql_query($sql) or die( mysql_error());
        }

显然,我正在努力查找 SQL 部分——我想知道是否没有一些内置的 SQL 函数来执行此操作或类似的功能?

4

4 回答 4

1

检查您是否在过去 24 小时内投票:

SELECT * 
FROM vote 
WHERE vote_fb_uid = '$this->fb_uid'
AND   FROM_UNIXTIME(vote_time) >= DATE_SUB(NOW(), INTERVAL 1 DAY)

如果您想限制在同一天(意味着您可以在 2013.05.21 23:55 和 2013.05.22 00:05 发布)

SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND   DATE(FROM_UNIXTIME(vote_time)) = DATE(NOW())
于 2013-05-22T11:18:05.070 回答
0

CURDATE()

将当前日期作为 ' YYYY-MM-DD' 或YYYYMMDD格式的值返回,具体取决于函数是在字符串还是数字上下文中使用。

mysql> SELECT CURDATE();
        -> '2008-06-13'
mysql> SELECT CURDATE() + 0;
        -> 20080613
于 2013-05-22T11:15:10.063 回答
0

尝试这个:

 $today = date('Y-m-d'); //change it to timestamp if you want in timestamp
 $sql = "
        SELECT count(*) as total FROM vote WHERE
        vote_fb_uid = '$this->fb_uid' and
        vote_time = '$today'";

        $res = mysql_query($sql) or die( mysql_error());


        if($res[0]['total'] < 1){
                $sql = sprintf("
            INSERT INTO vote(
            vote_fb_uid,
            vote_time)
            VALUES ('%s','%s')",
            mysql_real_escape_string($this->fb_uid),
            mysql_real_escape_string($this->time));

            $res = mysql_query($sql) or die( mysql_error());
            } else{
        //return error("custom","","Already Inserted.");    
        echo "already inserted";
    }
于 2013-05-22T11:18:11.877 回答
0

您的$sql查询有语法错误,您使用了两个时间子句WHERE正确的语法在 where is used 中使用两个或多个子句 AND来加入它们,只获取今天没有条目的记录,您可以使用DATE_SUB1 天的时间间隔

SELECT * 
FROM vote 
WHERE vote_fb_uid = '$this->fb_uid',
AND vote_time <= DATE_SUB(vote_time, INTERVAL 1 DAY)
于 2013-05-22T11:19:45.370 回答