doulanyan6455 2017-12-31 00:10
浏览 61
已采纳

PHP:PDO rowCount()有时返回0? [重复]

This question already has an answer here:

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;
</div>
  • 写回答

1条回答 默认 最新

  • dr200166 2018-01-01 22:22
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?