if else,fetchRow()zend

时间:2012-08-08 18:43:09

标签: php zend-framework

public function updateMemberdetail(Application_Model_Memberdetail $memberdetail)
{
    $data = array(
        'memberid' => $memberdetail->getMemberid(),
        'membername' => $memberdetail->getMembername(),
        'contact' => $memberdetail->getContact(),
        'birthday' => $memberdetail->getBirthday(),
        'email' => $memberdetail->getEmail(),
        'address' => $memberdetail->getAddress(),
    );

    $auth= Zend_Auth::getInstance(); //declare zend_auth to get instance
    $user= $auth->getIdentity(); //get identity of user
    $userid = $user->userid; //get userid of user

    $this->select() //select from usertable and memberdetail 
    ->from(array('memberdetail', 'usertable')) //join memberdetail and usertable through memberid = username 
    ->where('memberdetail.memberid = usertable.?', $userid); 
    $row = $this->fetchRow($select);
    if ($row == true) //if row exist update row
    {

        $this->update($data, 'memberid = '. (int)($memberdetail->getMemberid()));

    }
    else
    {

        $this->insert($data); //if row doesnt exist, add it

    }
}

您好,我在if else语句中遇到了一些问题。如果数据库中不存在数据,我想添加一行数据,但如果存在则更新它。但是,当我在DB中没有行时,它不会插入它。当我手动将一行插入数据库时​​,它会更新该行。

1 个答案:

答案 0 :(得分:1)

fetchRow方法将返回Zend_Db_Table_Row_Abstract的实例,如果未找到则返回NULL。从Zend的manual开始,我相信您需要在保存之前创建该行。

  $select = $this->select() //select from usertable and memberdetail 
    ->from(array('memberdetail', 'usertable')) //join memberdetail and usertable through memberid = username 
    ->where('memberdetail.memberid = usertable.?', $userid); 
  $row = $this->fetchRow($select);
  if (empty($row)) //if row exist update row
  {
    $newRow = $this->createRow($data);
    $newRow->save(); //if row doesnt exist, add it
  }
  else
  {
    $this->update($data, 'memberid = '. (int)($memberdetail->getMemberid()));
  }