首页 > 解决方案 > 为什么 SQL 查询不能通过并报错?

问题描述

我有这个表的数据库

users 
  user_id 
  user_name 
  user_email
  user_password 
  user_reg_date 

我有第二张表 user_tokens

user_tokens 
  token_id 
  token_user_id
  token_user_agent 
  toke_hash 
  token_created 
  token_expires 

外键 token_user_id 是对 user_id 的引用

php代码在这里

    $sql = 'INSERT INTO user_tokens 
            (token_user_id, token_user_agent, token_hash, token_created, token_expires) 
            VALUES (:userid, :uagent, :thash, :tcurrent, :texpires)';

            $ua = serialize($visitor->get_userspecs());
            $time = intval(time());

            $binder = array(
                ':userid'           => $userid,
                ':uagent'           => serialize($visitor->get_userspecs()),
                ':thash'            => $userhash,
                ':tcurrent'         => time(),
                ':texpires'         => strtotime('+2 Days')
            );

            $this->preAction($sql, $binder);

            if(!$this->doAction()) {

                return null;
            }

php 请求正在使用 PDO

    $this->stmt = $this
                ->get_con()
                ->prepare($this->sql);

            if (!$this->stmt) 
                throw new RuntimeException('SQL preparing failure! '.$stmt->errorCode());

            if (!empty($this->prepared)) {

                foreach ($this->prepared as $key => $value) {

                    $this->stmt->bindParam($key, $value);
                }
            } 

            $check = $this->stmt->execute();

我知道,当我打印 $binder -> 通过 print_r $user_id 显示 4 这与 users -> user_id 我得到的相同

当我尝试执行 sql 时出现错误

SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(`modulecms`.`user_tokens`,CONSTRAINT`user_tokens_ibfk_1` FOREIGN KEY(`token_user_id`)参考`users`(`user_id `))

在日志中我得到了这个

  2020-01-06T18:50:47.015764Z      26 Prepare   SELECT token_hash as token 
                FROM user_tokens WHERE token_user_id = ? LIMIT 1
2020-01-06T18:50:47.015803Z    26 Close stmt    
2020-01-06T18:50:47.015826Z    26 Execute   SELECT token_hash as token 
                FROM user_tokens WHERE token_user_id = '4' LIMIT 1
2020-01-06T18:50:47.015987Z    26 Close stmt    
2020-01-06T18:50:47.016396Z    26 Prepare   INSERT INTO user_tokens 
            (token_user_id, token_user_agent, token_hash, token_created, token_expires) 
            VALUES (?, ?, ?, ?, ?)
2020-01-06T18:50:47.016467Z    26 Execute   INSERT INTO user_tokens 
            (token_user_id, token_user_agent, token_hash, token_created, token_expires) 
            VALUES ('1578509447', '1578509447', '1578509447', '1578509447', '1578509447')
2020-01-06T18:50:47.017541Z    26 Close stmt

我的问题是什么?为什么我用时间戳重写了所有占位符?

标签: phpmysql

解决方案


推荐阅读