如何同时将记录更新为两个表?

时间:2015-08-10 08:20:45

标签: php pdo

我这里有更新代码,但我想同时更新两个表。我怎么能这样做?

以下是我尝试的代码

public function update($user_id,$username,$password,$province)
{
  try
  {
    $stmt=$this->db->prepare("UPDATE login, sample SET login.username=:username,login.password=:password,login.province=:province sample.username=:username,sample.password=:password WHERE login.user_id=:user_id and sample.id=:id");
    $stmt->bindparam(":username",$username);
    $stmt->bindparam(":password",$password);
    $stmt->bindparam(":province",$province);
    $stmt->bindparam(":user_id",$user_id);
    $stmt->bindparam(":id",$id);
    $stmt->execute();
    return true;
  }
  catch(PDOException $e)
  {
    echo $e->getMessage();
    return false;
  }
}

2 个答案:

答案 0 :(得分:0)

试试这个

update db1 inner join db2 on db1.username = db2.username 
   set db1.user_level = 1,
       db2.user_level = 1
  where db1.username = 'a';

答案 1 :(得分:0)

您需要将两个查询包装在事务中。阅读更多:http://php.net/manual/en/pdo.transactions.php