Richard
Richard

Reputation: 6126

PHP PDO Max Value

So let's say I have a column called groupID, it is a number given to a group of people. Basically all I want to do is get the largest value from that column, add 1 and store that input into a variable in php.

For example, if the last group's id was 5, then the next group's id should be 6. Any ideas?

$gid = $link->prepare("SELECT MAX(Group_ID) FROM Conference");
$gid->execute();
$groupid = $gid->fetchColumn();

$stmt = $link -> prepare("INSERT INTO Conference (`Group_ID`) VALUES (:groupid)");
$stmt->bindParam(':groupid', $groupid);
$stmt->execute();

Upvotes: 1

Views: 8913

Answers (3)

GautamD31
GautamD31

Reputation: 28753

Try like

$gid = $link->prepare("SELECT MAX(Group_ID) as maximum FROM Conference");

Upvotes: 1

Vikram Jain
Vikram Jain

Reputation: 5588

$gid = $link->prepare("SELECT MAX(Group_ID) FROM Conference");

$stmt = $link -> prepare("INSERT INTO Conference(Group_ID) SELECT MAX(Group_ID) FROM Conference");

$stmt->execute();

Upvotes: 1

Jon
Jon

Reputation: 437684

It would be much simpler to use an AUTO_INCREMENT column, when you wouldn't have to concern yourself with this at all.

To solve it manually, SELECT MAX(id) FROM table will give you the largest id currently in use, and adding +1 to that would achieve the goal. This is susceptible to race conditions (what if two clients do this and get the same value from MAX()?), but the recovery mode is very simple: repeat until successful.

Upvotes: 3

Related Questions