获取数据库表中列的最大值

I'm trying to get the max value of a column in a database table.

This is my PHP:

$st = mysql_fetch_assoc(mysql_query("SELECT max(`version`) FROM `remembers` WHERE id='$id'"));
$version = $st['version'] + 1;

So that should get the current version of id and then update it but adding 1 to it. But $st['version'] seems to be returning 0 when in the database the current highest is 1

Am I doing this wrong? Is there a better way to archive this?

You have to alias the MAX() selection in SQL in order to reference it in PHP:

SELECT max(`version`) AS version FROM ...

Also, mysql_fetch_assoc returns an array of arrays, so you cannot simply reference $st['version'] directly. Instead, you can change your PHP to:

$st = mysql_fetch_row(mysql_query("SELECT max(`version`) AS version FROM `remembers` WHERE id='$id'"));
$version = $st[0] + 1;

SQL has a function call max() and you are using it in the right context. You are so close to doing it right!

You just need to use the AS keyword.

SELECT max(version) AS max_version FROM remembers WHERE id='$id'