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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!