I have the following query:
$year = 2019;
$month = 6;
$stmt = $db->prepare(\'INSERT INTO officeRechNr (jahr,monat,zahl) VALUES (?,?,1)
The problem is that LAST_INSERT_ID(...);
with an argument doesn't return the generated ID but instead set the given value in the "memory" of LAST_INSERT_ID()
and returns it. So, in your first execution no auto incremented ID was generated (you provided the value by yourself) and LAST_INSERT_ID()
return 0
. In your following executions you save the value next+1
in the internal storage of LAST_INSERT_ID()
, which returns the value. This behavior is described in the MySQL in 12.14 Information Functions:
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID().
In fact, you can skip the LAST_INSERT_ID()
call and work without it.
INSERT INTO
officeRechNr (jahr,monat,zahl)
VALUES
(?,?,1)
ON DUPLICATE KEY UPDATE zahl = zahl+1
This will insert the row (with the given value) or increase the counter.
If you want the current counter for a given year and month you run a simple SELECT statement. Keep in mind that you might need transactions or locks because a different client could increase the counter before you fetched it with the SELECT statement.