不使用内部联接与PDO更新两个表?

时间:2015-08-13 00:54:50

标签: php pdo

我想使用PDO更新两个表。

  

SQLSTATE [HY093]:参数号无效:绑定变量数与令牌数不匹配

我想在两个表中同时更新用户名和密码。两者都有一个user_id字段。

public function update($user_id, $username, $password, $province) {
    try {
        $stmt = $this->db->prepare("UPDATE login INNER JOIN sample ON sample.username = sample.username SET login.username = :username, sample.username=:username WHERE user_id=:user_id");
        //$stmt=$this->db->prepare("UPDATE login SET username=:username,password=:password,province=:province WHERE user_id=:user_id");
        $stmt->bindparam(":username", $username);
        $stmt->bindparam(":password", $password);
        $stmt->bindparam(":province", $province);
        $stmt->bindparam(":user_id", $user_id);
        $stmt->execute();

        return true;
    } catch (PDOException $e) {
        echo $e->getMessage();
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

您需要更改准备好的查询,如下所示

UPDATE login INNER JOIN sample ON (login.user_id = sample.user_id)
SET login.username = :username, sample.username = :username
WHERE login.user_id = :user_id AND sample.user_id = :user_id

这是a visual explanation of SQL Joins