• 1st July 2009 - By admin

    Have run into a few problems recently with various aspects of CakePHP – the main one is CakePHP writing random rows to a table when calling the save() method for a model.

    For example:

    function addfriend($user_id, $friend_id) {
     
    	$this->data['Friend']['user_id'] = $user_id;
    	$this->data['Friend']['friend_id'] = $friend_id;
    	$this->data['Friend']['accepted'] = 0;
    	$this->data['Friend']['rejected'] = 0;
     
    	$this->User->Friend->Create();
     
    	if($this->User->Friend->save($this->data)){
    		echo ("Friend Added");
    	} else {
    		echo ("Error Adding Friend");
    	}
     
    }

    Will cause several rows to be written to the database when only one is required. This is because there is no redirect / exit statement so the script is trying to return to the same page and method several times.

    However this code will work correctly:

     
    function addfriend($user_id, $friend_id) {
     
    	$this->data['Friend']['user_id'] = $user_id;
    	$this->data['Friend']['friend_id'] = $friend_id;
    	$this->data['Friend']['accepted'] = 0;
    	$this->data['Friend']['rejected'] = 0;
     
    	$this->User->Friend->Create();
     
    	if($this->User->Friend->save($this->data)){
    		$this->Session->setFlash('Friend Added');
    		$this->redirect('users/view/'.$user_id);
    		exit;
    	} else {
    		$this->Session->setFlash('Error Adding Friend');
    		exit;
    	}
    }
    Share with your friends and help out this site:
    • Digg
    • del.icio.us
    • Facebook
    • Google Bookmarks
    • E-mail this story to a friend!
    • LinkedIn
    • Live
    • Reddit
    • StumbleUpon
    • Twitter
    • Yahoo! Bookmarks

Ad