Shawn31313
Shawn31313

Reputation: 6052

Getting the Max value of a column in a database table

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?

Upvotes: 2

Views: 3341

Answers (2)

Zane Bien
Zane Bien

Reputation: 23135

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;

Upvotes: 5

Jared Drake
Jared Drake

Reputation: 1002

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'

Upvotes: 1

Related Questions