views:

62

answers:

2

My logout function needs to update the latest row of a list of logins.

This is what I have came up with, however it doesn't even pass syntax validation.

$query =
    'UPDATE user_logins
     SET active = 0
     WHERE user_id = ' . Database::instance()->escape($this->getCurrentUserId()) . '
     AND datetime = MAX(datetime) LIMIT 1';

Essentially there may be 30 or so with the same user_id value. I'd only like to update the last login. This will obviously be the most recent datetime value.

What am I doing wrong?

A: 

You would have to use a subquery for this.

$query =
    'UPDATE user_logins
     SET active = 0
     WHERE user_id = ' . Database::instance()->escape($this->getCurrentUserId()) . '
     AND datetime = (SELET MAX(datetime) FROM user_logins WHERE user_id = '' . Database::instance()->escape($this->getCurrentUserId()) . ') LIMIT 1';

Or something like this.

Edit: As the comment states, this will not work because of lack of support in MySQL. I'll leave this answer for the reference.

Ikke
Unfortunately this won't work with MySQL. You'll get an error `Error 1093 (ER_UPDATE_TABLE_USED)` (see http://dev.mysql.com/doc/refman/5.0/en/subquery-errors.html)
Peter Lang
In the subquery you also need to add the user id condition, otherwise you will get the maximum datetime from anyone not the current user.
Oliver Hanappi
Hmm, mysql still has a lot to add.
Ikke
Yes, definitely :)
Peter Lang
this approach really seems overkill to me. Why not simply sort the column by datetime first, then select the topmost row as my solution proposes?
pixeline
+1  A: 

This should work, provided your datetime column is a timestamp or a datetime type field.

$query =
    'UPDATE user_logins
     SET active = 0
     WHERE user_id = ' . Database::instance()->escape($this->getCurrentUserId()) . '
     ORDER BY datetime DESC LIMIT 0,1';
pixeline
+1 for speed. Dang. I'll delete my duplicate answer, and learn to type faster :)
Frank Shearar