1

I am using the fantastic last_insert_id trick described here, but now run into the problem of non-deterministic behavior.

The PHP code works approximately every other time I run it. This is on a completely idle system (no production running simultaneously).

Is there anything I am forgetting here? What could the problem be?

My PHP code:

$query = "UPDATE `session` 
                SET `date_access` = NOW(), someField = LAST_INSERT_ID(someField) 
                WHERE ID = :cookie LIMIT 1 ;";
    $stmt = $dbh->prepare($query);
    $stmt->bindParam(':cookie', $_COOKIE['x']);
    if ($stmt->execute()) {
        $count = $stmt->rowCount();
        if ($count == 1) {
            $result = $dbh->lastInsertId();
        } 
    }

The code is run with an existing "cookie" value every time, but the $count is 0 (instead of 1) every other time the code runs.

And this is the table:

            SET NAMES utf8;
            SET time_zone = '+00:00';
            SET foreign_key_checks = 0;
            SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';

            SET NAMES utf8mb4;

            DROP TABLE IF EXISTS `session`;
            CREATE TABLE `session` (
              `ID` char(50) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
              `date_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
              `date_access` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              `someField` bigint(20) unsigned NOT NULL,
              UNIQUE KEY `ID` (`ID`),
              KEY `someField` (`someField`),
              CONSTRAINT `session_ibfk_2` FOREIGN KEY (`someTable`) REFERENCES `someTable` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Swiss Mister
  • 3,260
  • 2
  • 20
  • 42
  • Update will return 0 rows (via `rowCount`) if there were *no matching rows updated*. This must mean that in some of the runs (ie. the first with each cookie?) there is no matching cookie value currently in the database. – user2864740 Dec 31 '17 at 00:17
  • 2
    Addendum to above: it could also be that *none of the values changed*; ref https://stackoverflow.com/questions/35364214/does-mysql-overwrite-a-column-of-same-value-on-update IIRC, it also depends on the "CLIENT_FOUND_ROWS" flag. – user2864740 Dec 31 '17 at 00:30
  • 1
    What is the idea behind setting `someField` to `LAST_INSERT_ID(someField)` in your `UPDATE` query? From [the manual](https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id): *"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()."* Are you sure that's what you want? – rickdenhaan Dec 31 '17 at 01:19
  • @rickdenhaan: As described in the SO answer I linked to, this is a way to retrieve the ID without having to run another select statement. I want to reduce the number of DB calls. – Swiss Mister Dec 31 '17 at 10:13
  • @user2864740: that is one very hot hint - thanks! I will investigate. That might exactly be the issue. – Swiss Mister Dec 31 '17 at 10:15
  • 1
    @user2864740: yours is the answer! If you make your "Addendum" into a proper SO answer, I will accept and promote it. Thanks a huge lot! I would never have guessed this! – Swiss Mister Dec 31 '17 at 10:51
  • 1
    https://dev.mysql.com/doc/refman/5.7/en/mysql-affected-rows.html "*For UPDATE statements, the affected-rows value by default is the number of rows actually changed.*" – Bill Karwin Jan 01 '18 at 18:54
  • 1
    Thanks @BillKarwin - see user2864740's answer. It contains your hint plus the one at the flag... Make this into a proper answer and I'll accept it. – Swiss Mister Jan 01 '18 at 20:16

1 Answers1

1

https://dev.mysql.com/doc/refman/5.7/en/mysql-affected-rows.html says:

For UPDATE statements, the affected-rows value by default is the number of rows actually changed.

In other words, if you UPDATE but the values you set are already the values stored in the matching row, it does not count as a row affected.

This is the default behavior, but you can change this behavior if you set a PDO attribute when you connect. See PHP, MySQL - can you distinguish between rows matched and rows affected?

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828