GFL
GFL

Reputation: 1446

Get a number inserted or updated into a table

What's the best way to get a number I'm inserting or updating into my database? I'm trying to figure out what count ended up being after this insert:

$pdo = $db->prepare('INSERT INTO dailies (day, count) VALUES (:day, 1) ON DUPLICATE KEY UPDATE count = count+1');
$pdo->execute(array(':day'=>date('z')));

I'm trying to do a fetch, but its not working. I'm guessing because this is an insert or update and not a select.

$fetch = $pdo->fetch(PDO::FETCH_ASSOC);

Upvotes: 0

Views: 36

Answers (1)

Sasha Pachev
Sasha Pachev

Reputation: 5336

You can do something like this with user variables:

INSERT INTO dailies (day, count) VALUES (:day, 1) ON DUPLICATE KEY UPDATE count = (@new_count = count+1)

Then

SELECT @new_count

If the record was inserted, @new_count will contain the value you set in the update. Otherwise it will come back as NULL.

Upvotes: 1

Related Questions