Refresh problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • seralasu
    New Member
    • Oct 2006
    • 34

    Refresh problem

    Hi,
    I have refresh problem.When user does refresh or clicks F5 then form variables again posting. It crates same a lot of inserts. I don't know How to solve it.
  • ak1dnar
    Recognized Expert Top Contributor
    • Jan 2007
    • 1584

    #2
    I think you are using a html form to submit the data and there might be a submit button.
    Let's assume that submit button is like this.

    [HTML]<input type="submit" name="sub" value="Send">[/HTML]

    then from your php side use like this.

    [PHP]if ($_POST['sub'])
    {
    // insert current coding inside this if block for getting values from html form and //inserting it to the database
    }[/PHP]

    php will execute only user cllicks the sub button .

    Comment

    • seralasu
      New Member
      • Oct 2006
      • 34

      #3
      I have already done it. My code sample;
      Submit buton definition
      <input type="submit" name="kaydet" value="Kaydet">

      insertion side

      if($_POST['kaydet'] )
      {
      // I'm taking POST variables and inserting to database
      }

      Comment

      • ak1dnar
        Recognized Expert Top Contributor
        • Jan 2007
        • 1584

        #4
        Good for you. :D

        Comment

        • Purple
          Recognized Expert Contributor
          • May 2007
          • 404

          #5
          Hi seralasu,

          I am assuming you are still having a problem with this.. a suggestion is to use Javascript on the onClick event of your submit button and set a hidden field on your form and test that rather than the submit button - the onClick event will only fire when clicked - ie it does not fire on refresh / F5..

          the following code demonstrates using a basic javascript alert..
          [PHP]
          echo "<form name=\"test\" action=\"".$_SE RVER["PHP_SELF"]."\" method = \"post\">
          <input type=\"submit\" name=\"kaydet\" value=\"Kaydet\ " onClick=\"javas cript:alert('he re');\"></input></form>";
          print_r($_POST) ;
          [/PHP]

          Comment

          • subash
            New Member
            • Sep 2006
            • 32

            #6
            Hi,

            Please check the thread http://www.thescripts. com/forum/thread576526.ht ml

            Subash :)

            Comment

            • Purple
              Recognized Expert Contributor
              • May 2007
              • 404

              #7
              Hi Subash,

              I don't think the thread you referenced answers the initial issue - the problem experience is caused by hitting refresh or F5 on a form using a method of post - basically the form is submitted every time the form is refreshed, F5 is hit or the submit button is pressed..

              Rgds Purple

              Comment

              • pbmods
                Recognized Expert Expert
                • Apr 2007
                • 5821

                #8
                Easiest way I can think of to prevent this is to set up some unique keys in MySQL.

                For example, suppose you had a table that looked something like this:

                Code:
                mysql> DESCRIBE `Data_Categories`;
                +------------+---------------------+------+-----+---------+----------------+
                | Field      | Type                | Null | Key | Default | Extra          |
                +------------+---------------------+------+-----+---------+----------------+
                | categoryid | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment | 
                | desc       | varchar(64)         | NO   |     |         |                | 
                +------------+---------------------+------+-----+---------+----------------+
                Obviously, it wouldn't be useful to have a bunch of duplicate categories (this is an example; bear with me). So we would want to add a unique constraint so that every category has a different name.

                To set up a unique key:
                Code:
                ALTER TABLE `Data_Categories` ADD UNIQUE KEY `catName`(`desc`);
                The `catName` is just the name of your key and can be just about anything you want it to be. You put the name of the column(s) you want constrained inside the parenthesis.

                Once the unique is in place, attempting to insert a duplicate row will fail:

                Code:
                mysql> INSERT INTO `Data_Categories` (`desc`) VALUES('Tester');
                Query OK, 1 row affected (0.00 sec)
                
                mysql> INSERT INTO `Data_Categories` (`desc`) VALUES('Tester');
                ERROR 1062 (23000): Duplicate entry 'Tester' for key 2
                [EDIT: Just to make things complicated, you can put a constraint on more than one column in the table. For example, if you used:

                Code:
                ALTER TABLE `Data_Categories` ADD UNIQUE KEY `parentData`(`parent`, `desc`);
                (assuming that `Data_Categorie s` also had a `parent` field)

                Then an INSERT would only fail if you tried to add a row with the same `parent` AND `desc` as an existing row, but would still allow the INSERT if only one of the fields matched.]

                Comment

                • seralasu
                  New Member
                  • Oct 2006
                  • 34

                  #9
                  Hi,
                  Thanks for all replies. I will try them.

                  Comment

                  • paja
                    New Member
                    • Jun 2007
                    • 1

                    #10
                    If($_POST['sub']) does not work

                    To AJAXRAND (sorry - I could not post this as a reply to your comment)

                    It does not work. Your $_POST['sub'] will be still there (the form will be sent again with F5 - refresh).

                    Have a try to add at the end of your PHP script this:
                    echo "<PRE>POST :";
                    print_r($_POST) ;
                    echo "</PRE>";

                    Paja
                    Last edited by paja; Jun 30 '07, 02:55 PM. Reason: wanted to reply to a note, was added at the end of discussion

                    Comment

                    • kovik
                      Recognized Expert Top Contributor
                      • Jun 2007
                      • 1044

                      #11
                      Originally posted by ajaxrand
                      I think you are using a html form to submit the data and there might be a submit button.
                      Let's assume that submit button is like this.

                      [HTML]<input type="submit" name="sub" value="Send">[/HTML]

                      then from your php side use like this.

                      [PHP]if ($_POST['sub'])
                      {
                      // insert current coding inside this if block for getting values from html form and //inserting it to the database
                      }[/PHP]
                      Whoa whoa whoa. NEVER use the submit button as the condition of submission. A form can be submitted without use of the submit button, and the condition will never be met (this is an IE bug, so we can't ignore it).

                      As for the problem of this post, it is hardly a problem at all. It's just the way that HTTP POST works. It exists on the page that was posted to, and refreshing will re-submit data no matter what the situation. Since your problem is that your submission causes more database entries, try these:

                      1) Check the database for that entry before adding it in.
                      [code=php]$result = mysql_query("SE LECT `id` FROM `table` WHERE `var1` = '" . mysql_real_esca pe_string($_POS T['var1']) . "';");

                      if(mysql_num_ro ws() == 0)
                      {
                      // Perform insertion
                      }
                      [/code]

                      2) Create a hidden field that is filled upon posting and check for it
                      [code=php]if(!empty($_POS T) && isset($_POST['alreadyposted'] && $_POST['alreadyposted'] == 0)
                      {
                      $alreadyposted = true;
                      // Handle the post
                      }

                      ....

                      <form>
                      <input type="hidden" name="alreadypo sted" value="<?php echo isset($alreadyp osted) ? 1 : 0; ?>" />[/code]

                      Comment

                      • ak1dnar
                        Recognized Expert Top Contributor
                        • Jan 2007
                        • 1584

                        #12
                        I Think, I made a Bad mistake without reading seralasu's Problem well.
                        Sorry for that.

                        seralasu,
                        Do you prefer to redirect the Page after submitting the form to another location or to the same page.

                        [CODE=php]
                        <?
                        $con = mysql_connect(' localhost', 'root', 'dba') or die ("Could not connect to the Database");
                        mysql_select_db ('test', $con) or die (mysql_error()) ;

                        if(isset ($_POST['insert']) && $_POST['productname'] != "" ){
                        $STR_NAME = $_POST['productname'];
                        $SQL_INSERT = "INSERT INTO products (p_name) VALUES ('$STR_NAME')";
                        mysql_query($SQ L_INSERT) or die(mysql_error ());
                        header('Locatio n:'.$PHP_SELF.' ');
                        // You Can redirect to Another Page Also
                        //header('Locatio n: thankyou.php');
                        }
                        ?>
                        <html>
                        <body>
                        <form action="
                        <input name="productna me" type="text">
                        <input name="insert" type="submit">
                        </form>
                        </body>
                        </html>[/CODE]

                        Comment

                        • kovik
                          Recognized Expert Top Contributor
                          • Jun 2007
                          • 1044

                          #13
                          Originally posted by ajaxrand
                          [CODE=php]header('Locatio n:'.$PHP_SELF.' ');[/CODE]
                          *Ahem* Umm... I really didn't think there'd be need to contradict a mod twice in the same post. I hope it doesn't seem rude, but these are points of security and usability.

                          $SERVER['PHP_SELF'] and it's deprecated global counterpart, $PHP_SELF, are unsafe and inconsistent. They cause different outputs on CGI installations. It is unsafe because it openly allows XSS. An alternative to $_SERVER['PHP_SELF'], in the sense that most people use it for, is basename(__FILE __).

                          Also, header() is not meant to accept relative paths. Browsers are not required, by standards, to accept and translate relative paths through redirection. You must always give an absolute path when using header() redirection.

                          Comment

                          • phpmike
                            New Member
                            • May 2007
                            • 5

                            #14
                            I believe the answer is here:
                            It uses sessions to hold a secret code and verifies on the form handle. It then creates a new secret code and overwrites the session so if the form is refreshed the two codes do not match.

                            php no refresh script

                            Comment

                            • ak1dnar
                              Recognized Expert Top Contributor
                              • Jan 2007
                              • 1584

                              #15
                              Originally posted by volectricity
                              *Ahem* Umm... I really didn't think there'd be need to contradict a mod twice in the same post. I hope it doesn't seem rude, but these are points of security and usability.

                              $SERVER['PHP_SELF'] and it's deprecated global counterpart, $PHP_SELF, are unsafe and inconsistent. They cause different outputs on CGI installations. It is unsafe because it openly allows XSS. An alternative to $_SERVER['PHP_SELF'], in the sense that most people use it for, is basename(__FILE __).

                              Also, header() is not meant to accept relative paths. Browsers are not required, by standards, to accept and translate relative paths through redirection. You must always give an absolute path when using header() redirection.
                              I really appreciate your feedback volectricity ! Thanks.

                              And it’s a good point to start a new thread for Good and Bad PHP Code here at PHP Forum.

                              Thanks,
                              -Ajaxrand

                              Comment

                              Working...