开发者

Trouble comparing strings in MySQL

I have the field date in my MySQL DB as a string, and I want to compare it to another string in a MySQL query to get the recent activity for a user within a week. But for some reason I am getting no returned data from the fetch_assocs.

Please can you tell me where I am going wrong?

$week = uk_date();
    echo $week . " - ---------- -";
    $week = $week - (60*24*7);
    echo $week;
    $array = array();
    $q = mysql_query("SELECT * FROM Posts WHERE `date` > " . $week . "") or die(mysql_error());
    if (!$q) {}
    if (mysql_num_rows($q) < 1) {

    }
    else {
        while ($row = mysql_fetch_assoc($q)) {
            $array['posts'][] = $row;
        }
    }
    $q = mysql_query("SELECT * FROM Comments WHERE `date` > " . $week . "") or die(mysql_error());
    if (mysql_num_rows($q) < 1) {

    }
    else {
        while ($row = mysql_fetch_assoc($q)) {
            $array['comments'][] = $row;
        }
    }
    $q = mysql_query("SELECT * FROM Likes WHERE `date` > " . $week . "") or die(mysql_error());
    if (mysql_num_rows($q) < 1) {

    开发者_如何学JAVA}
    else {
        while ($row = mysql_fetch_assoc($q)) {
            $array['likes'][] = $row;
        }
    }


"I have the field date in my MySQL DB as a string,"... your date field is a char/varchar/text? That means you will NOT be able to do direct date/time calculations, because you're not using date/time values. If you're storing dates in a field, then make that field a date or datetime type.

Then you can do stuff like:

SELECT ... FROM ... WHERE `datefield` > DATE_SUB(now(), INTERVAL 1 WEEK)


Don't calculate the week in PHP at all - that's something the database can do, e.g.

SELECT * FROM Comments WHERE date > date_sub(CUR_DATE(), interval 7 day);

See http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff to learn about the magic of MySQL Date operations.


Instead of simple date try to use STR_TO_DATE(date) in mysql query and for week try to use php function strtotime("-1 week");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜