0

I have a relatively simple class which deletes a post:

function delete_post($postid, $reason){

    //Stuff to delete post      
    $this->delete_response = 'Thanks, your course has been removed.';

}

This function is called at the top of a page with a form on. If the form is submitted, the same page checks the POST[] and carries out the function, like so:

if(!empty($_POST['removecourse'])){
    $courseManager->delete_post($_POST['courseid'], $_POST['cancel-reason']);
    echo $courseManager->delete_response;
}; 

So my problem is... when I refresh the page, the message keeps displaying. I know this is because I am re-submitting the form, and because there is no such P/R/G pattern going on, but as i am new to OOP, im wondering if im doing this the right way, or if anyone could suggest a way similar to PRG or something?

JamesG
  • 2,018
  • 2
  • 28
  • 57
  • Is there any reason you can't use P/R/G? (just curious) – jprofitt Jun 27 '12 at 14:14
  • 1
    You could add a little checking inside `delete_post` - count the number of items that are deleted, and set the response to an empty string if there was nothing deleted. – andrewsi Jun 27 '12 at 14:14
  • @jprofitt hi, I would gladly use PRG but I was not sure how to implement it in the OOP way I have done this :/. I am new to OOP having done everything previously in a procedural fashion. – JamesG Jun 27 '12 at 14:27

1 Answers1

1

Add an if that test if somthing changed, like mysql_affected_rows

function delete_post($postid, $reason)
{
    //Stuff to delete post
    if(mysql_affected_rows())
    {
       $this->delete_response = 'Thanks, your course has been removed.';
    }
}
Puggan Se
  • 5,738
  • 2
  • 22
  • 48
  • Ahh ok, and would this be a "best practice" kinda of way? – JamesG Jun 27 '12 at 14:26
  • 1
    The good approach would be to generate token (hash), store it in the session of the current user and place it to the hidden form field, later check it for validity and (if valid) remove it from $_POST array after deletion of the record, or regenerate it after simple page refreshing (in the session and in the hidden field of the form). Imagine situation - you're not removing record by ID, but adding some content. So, your record would be added as many times, as user updates the page... – BasTaller Jun 27 '12 at 14:59
  • Look at this answer, it's for Zend Framework, but the idea is clear enough due to the names of ZF methods: http://stackoverflow.com/a/2542782/411671 – BasTaller Jun 27 '12 at 15:05