How to post data to the same page

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fjm
    Contributor
    • May 2007
    • 348

    How to post data to the same page

    Well.. I'm back with another simple question but I'm not sure what the term is so I can't google it. I think it may have to do with $_SERVER[SELF]

    What I am after is a form that will insert data into a mysql database. What I want is for that page to display the html, the user would then enter the data, press submit and if there are any errors, remain on that page and show the errors in red. I think I have the errors down but what is happening is that when I press submit, I am being taken to a different page. Here are my simple scripts:

    [CODE=html] <html>
    <body>
    <form action="test.ph p" method="post">
    Firstname: <input type="text" name="firstname " />
    Lastname: <input type="text" name="lastname" />
    Age: <input type="text" name="age" />
    <input type="submit" />
    </form>
    </body>
    </html> [/CODE]

    and..

    [CODE=php]<?php
    include "connection.php ";
    $sql="INSERT INTO person (FirstName, LastName, Age)
    VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
    if (!mysql_query($ sql,$con))
    {
    die('Error: ' . mysql_error());
    }
    echo "1 record added";mysql_cl ose($con)
    ?> [/CODE]

    I have tried to combine both scripts into one but the sql is immediatley inserting a new record into the database *instead* of waiting until the submit button is pressed.

    Can someone please point me in the right direction or maybe tell me what the term to do this might be so I can google it?

    Please don't recommend Ajax. I know this can be done using Ajax but I prefer not to use it cuz I don't know it. :)

    Thanks
    Last edited by pbmods; Jun 23 '07, 11:58 PM. Reason: Changed code language. Thanks for using CODE tags!
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Heya, fjm.

    Originally posted by fjm
    I have tried to combine both scripts into one but the sql is immediatley inserting a new record into the database *instead* of waiting until the submit button is pressed.
    To prevent your SQL from getting executed, you'll want to enclose it in a conditional that checks to see if $_POST is valid:

    [code=php]
    if( ! (
    empty($_POST['firstname']) ||
    empty($_POST['lastname']) ||
    empty($_POST['age'])
    )) {
    include('connec tion.php');
    $sql="INSERT INTO person . . .
    .
    .
    .
    } else {
    ?>
    <html>
    .
    .
    .
    <?php } ?>
    [/code]

    Comment

    • fjm
      Contributor
      • May 2007
      • 348

      #3
      H pbmods..


      I did just that with something I found in one of my php books. Here is the code I have currently:

      Code:
      <?php
      if (isset($_POST['submit'])) {
      include "persist.php";
      $sql="INSERT INTO person (FirstName, LastName, Age)
      VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
       
      if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
      echo "1 record added";
      }
       
      mysql_close($con)
      ?>
      <html>
      <body>
      <form method="post" action="ro.php">
      Firstname: <input type="text" name="firstname" />
      Lastname: <input type="text" name="lastname" />
      Age: <input type="text" name="age" />
      <input name="submit" type="submit" />
      </form></body>
      </html>
      I see a couple of problems and I'm not sure if they can be overcome or not.

      First is the fact that if I attempt an insert of the data, it goes in fine. If I clear the text boxes and hit refresh, it attempts to enter the exact same data a second time. I don't know where it is storing the data because I cleared it from the boxes.

      Second is the mysql error. When I do the refresh as stated above it prints the error to a second page instaed of the page the html is on, which is where I would like it to be printed. Is it possibe to have the mysql error printed on the same page?

      Thanks again.

      Comment

      • pbmods
        Recognized Expert Expert
        • Apr 2007
        • 5821

        #4
        Heya, fjm.

        Originally posted by fjm
        I see a couple of problems and I'm not sure if they can be overcome or not.

        First is the fact that if I attempt an insert of the data, it goes in fine. If I clear the text boxes and hit refresh, it attempts to enter the exact same data a second time. I don't know where it is storing the data because I cleared it from the boxes.

        Second is the mysql error. When I do the refresh as stated above it prints the error to a second page instaed of the page the html is on, which is where I would like it to be printed. Is it possibe to have the mysql error printed on the same page?
        First problem is easy to overcome. You simply do your database stuff on a different page and then redirect to the original page after it is done executing.

        To solve the second problem, you'll want to save your $_POST variables into $_SESSION, try to save them to the database, then save a message to the $_SESSION and go back to your original form page.

        When you get back to the form, you display $_SESSION['messageOrWhate ver'] at the top (or wherever) to let the User know what happened (for example, "Your changes have been saved.", or "Please enter a valid age."). Then, you use $_SESSION['varname'] instead of $_POST['varname'] as the value for each input.

        Comment

        • fjm
          Contributor
          • May 2007
          • 348

          #5
          Originally posted by pbmods
          First problem is easy to overcome. You simply do your database stuff on a different page and then redirect to the original page after it is done executing.
          Ok.. that does sound easy. Do you mean to split the html out of the php? I am not shure how to redirect though. I will google that when I am done here.

          To solve the second problem, you'll want to save your $_POST variables into $_SESSION, try to save them to the database, then save a message to the $_SESSION and go back to your original form page.
          Like this?
          Code:
          <?php session_start(); 
          session_register ("submit"); 
          ?>
          When you get back to the form, you display $_SESSION['messageOrWhate ver'] at the top (or wherever) to let the User know what happened (for example, "Your changes have been saved.", or "Please enter a valid age."). Then, you use $_SESSION['varname'] instead of $_POST['varname'] as the value for each input.
          I'm lost here.. Do you mean echo the variable?

          Thanks for the help pbmods!!!!!

          EDIT:

          Woohoo.. I got the redirect working and now goes back to the html page. Now to just try and dicipher the last part of your post. to get the session working. :)

          I split the php from the html and I am thinking that I should be using the session in the php script. Am I correct on this?

          Comment

          • fjm
            Contributor
            • May 2007
            • 348

            #6
            I have successfully gotten for validation to work within this script as well. (Maybe I am making progress here?)

            I had to comment out the redirect to be able to see the errors generated from the validation and the mysql errors or sucess.

            I have attempted to work with the session to push my data over to the other php script but I can 't get it working. Can someone please offfer a hand.

            Here are my two scripts as they are.

            test4.php:
            Code:
            <?php
            //header( 'Location: ro.php' ) ;
            $errors = array();
            $page = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
            if (!$_POST['firstname'])
            	 $errors[] = "First name is required";
            if (!$_POST['lastname'])
            	 $errors[] = "Last name is required";
            if (!$_POST['age'])
            	 $errors[] = "Age is required";
             
            if (count($errors)>0){
            	 echo "<strong>ERROR:<br>\n";
            	 foreach($errors as $err)
            		echo "$err<br>\n";
            } else {
            		 include "persist.php";
            		 $sql="INSERT INTO person (FirstName, LastName, Age)
            		 VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
            		 if (!mysql_query($sql,$con))
            		 {
            			 die('Error: ' . mysql_error());
            		 }
            		 echo "1 record added";
             
            		 mysql_close($con);
            }
            ?>
            <?php
            ?>
            ro.php
            Code:
            <html>
            <body>
            <form method="post" name="submit" action="test4.php">
            Firstname: <input type="text" name="firstname" /><br />
            Lastname: <input type="text" name="lastname" /><br />
            Age: <input type="text" name="age" /><br />
            <input name="submit" type="submit" />
            </form></body>
            </html>
            What I am after is for all of the error warnings *and* the sucessful mysql insert messages to update into the "ro.php" file. pbmods suggested that I store these in the database?? I'm not sure what to do on this.

            Thank you for helping. Frank

            Comment

            • pbmods
              Recognized Expert Expert
              • Apr 2007
              • 5821

              #7
              Heya, Frank.

              Ok, you're looking great so far.

              And so is your code :)

              (A bass drum and a cymbal fell out of a tree. Ba-dum-ching!)

              Now to save the data to the session so you can share it between page loads.

              The easiest way to do this is to call this at the start of test4.php:
              [code=php]
              foreach($_POST as $key => $val)
              $_SESSION[$key] = $val;
              [/code]

              This will transfer over your $_POST variables to the $_SESSION.

              Likewise, you can use $_SESSION['errors'] instead of $errors.

              test4.php can then do its thing (but wherever you check $_POST, use $_SESSION instead. E.g., $_SESSION['firstname'] instead of $_POST['firstname']).

              Then in ro.php, you would echo $_SESSION['theVarThatYouW ant'] as the value for each of your inputs:

              [code=html]
              Firstname: <input type="text" name="firstname " value="<?php echo $_SESSION['firstname']; ?>" /><br />
              [/code]

              and so on.

              And to display the messages, you could do something like this:

              [code=php]
              if(! empty($_SESSION['errors'])) {
              print('<div class="errors"> ' . implode('<br />', $_SESSION['errors']) . '</div>');
              unset($_SESSION['errors']);
              }
              [/code]

              If there are any errors, this will display them (with each one separated by a '<br />'), then flush the errors array.

              Comment

              • fjm
                Contributor
                • May 2007
                • 348

                #8
                Argg.. Its all good. I have lost my hair and and parts of my body are now falling away. :)

                Well... pbmods.. I was one step a head of you before you posted. I actually had the sessions working. I was able to get the values to echo from one page to another. Really cool stuff man!

                I am still having a problem with the validation and mysql errors. Here is what I have and also I would like to tell you what I am reading about the way I have it set up. If you could please tell me if my huntch is correct, I think I may just be *understanding* a little better here. :)

                test4.php
                [CODE=php]<?php
                session_start() ;
                //$_SESSION['firstname'] = $_POST['firstname'];
                foreach($_POST as $key => $val)
                $_SESSION[$key] = $val;

                header( 'Location: ro.php' ) ;
                include "persist.ph p";

                $errors = array();
                $page = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
                if (!$SESSION['firstname'])
                $SESSION['errors'] = "First name is required";
                if (!$SESSION['lastname'])
                $SESSION['errors'] = "Last name is required";
                if (!$SESSION['age'])
                $SESSION['errors'] = "Age is required";

                if (count($errors) >0){
                echo "<strong>ERROR: <br>\n";
                foreach($errors as $err)
                echo "$err<br>\n ";
                } else {

                $sql="INSERT INTO person (FirstName, LastName, Age)
                VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
                if (!mysql_query($ sql,$con))
                {
                die('Error: ' . mysql_error());
                }
                echo "1 record added";

                mysql_close($co n);
                }
                ?>[/CODE]


                ro.php
                [CODE=php]<?php
                session_start() ;
                echo $_SESSION['err'];
                ?>
                <html>
                <body>
                <form method="post" name="submit" action="test4.p hp">
                Firstname: <input type="text" name="firstname " /><br />
                Lastname: <input type="text" name="lastname" /><br />
                Age: <input type="text" name="age" /><br />
                <input name="submit" type="submit" />
                </form></body>
                </html>[/CODE]

                Now. What I am seeing is that in file test4.php, I want to have the value of each of the variables in the array echo to ro.php. BUT... I see that because it is an array, the last line in the array "$err" would be the variable that holds the value. If this is correct, could it be the reason I cannot get the variables to echo? I know that the code itself is not correct but I just don't know where.

                Comment

                • pbmods
                  Recognized Expert Expert
                  • Apr 2007
                  • 5821

                  #9
                  Originally posted by fjm
                  Now. What I am seeing is that in file test4.php, I want to have the value of each of the variables in the array echo to ro.php. BUT... I see that because it is an array, the last line in the array "$err" would be the variable that holds the value. If this is correct, could it be the reason I cannot get the variables to echo? I know that the code itself is not correct but I just don't know where.
                  Quickie: You used $_SESSION['errors'] in test4.php, but $_SESSION['err'] in ro.php.

                  When you echo an array, the output will be 'Array'. Not very useful. So instead, we need to run through the array and output each element. Fortunately, there's a function that will help make this a lot easier.

                  [code=php]
                  if(! empty($_SESSION['errors'])) {
                  print('<div class="errors"> ' . implode('<br />', $_SESSION['errors']) . '</div>');
                  unset($_SESSION['errors']);
                  }
                  [/code]

                  The first line checks to see if $_SESSION['errors'] has any values. This would be useful, for example, so that we don't output an error div if there are no error messages.

                  The second line outputs a div, then uses implode() to compile all of the error messages in $_SESSION['errors'] and separates each one with a '<br />'.

                  So for example, if $_SESSION['errors'] looks like this:
                  [code=php]
                  $_SESSION['errors'] = array(
                  'Message 1',
                  'Message 2',
                  'Message 3'
                  );
                  [/code]

                  Then:
                  [code=php]
                  print(implode(' <br />', $_SESSION['errors']));
                  [/code]

                  Outputs:
                  Code:
                  Message 1<br />Message 2<br />Message 3
                  And then the last line unsets $_SESSION['errors'] so that we start over again with no messages.

                  In terms of the other variables, when you execute this block in test4.php:
                  [code=php]
                  foreach($_POST as $key => $val)
                  $_SESSION[$key] = $val;
                  [/code]

                  This copies each of your $_POST variables to $_SESSION. So $_SESSION['firstname'] = $_POST['firstname'], and so on.

                  To access your saved variables in ro.php, you would reference $_SESSION, just like you would in test4.php:

                  [code=html]
                  <input type="text" name="firstname " value="<?php echo $_SESSION['firstname']; ?>" />
                  [/code]

                  Comment

                  • fjm
                    Contributor
                    • May 2007
                    • 348

                    #10
                    pbmods,

                    I am closer than I have ever been.. Here is what I now have.. I have the error messages now being echoed to the main ro.php file after redirect. Woohoo.. I don't know if this looks right but would you or anyone for that matter please have a look.

                    ro.php
                    Code:
                    <?php
                    session_start();
                    echo $_SESSION['err'];
                    ?>
                    <html>
                    <body>
                    <form method="post" name="submit" action="test4.php">
                    Firstname: <input type="text" name="firstname" /><br />
                    Lastname: <input type="text" name="lastname" /><br />
                    Age: <input type="text" name="age" /><br />
                    <input name="submit" type="submit" />
                    </form></body>
                    </html>
                    test4.php
                    Code:
                    <?php
                    session_start();
                    $_SESSION['firstname'] = $_POST['firstname'];
                    $_SESSION['lastname'] = $_POST['lastname'];
                    $_SESSION['age'] = $_POST['age'];
                    header( 'Location: ro.php' ) ;
                    include "persist.php";
                    		  
                       $errors = array();
                       if (!$_POST['firstname'])
                    	  $errors[] = "First name is required";
                       if (!$_POST['lastname'])
                    	  $errors[] = "Last name is required";
                       if (!$_POST['age'])
                    	  $errors[] = "Age is required";
                    	  
                       if (count($errors)>0){
                    	  echo "<strong>ERROR:<br>\n";
                    	  foreach($errors as $_SESSION['err'])
                    		echo "$err<br>\n";
                       } else {
                    
                    		  $sql="INSERT INTO person (FirstName, LastName, Age)
                    		  VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
                    		  if (!mysql_query($sql,$con))
                    		  {
                    			  die('Error: ' . mysql_error());
                    		  }
                    		  echo "1 record added";
                      
                    		  mysql_close($con);
                       }
                    ?>
                    All I did was to set the $_SESSION in test4.php in the last line of the arrray. Is this ok and correct?

                    Comment

                    • fjm
                      Contributor
                      • May 2007
                      • 348

                      #11
                      Wow. Pbmods. I now see exactly what the line you provided does. It maintains state. :) I'm understanding a little more. Thank you!!
                      Code:
                      <input type="text" name="firstname" value="<?php echo $_SESSION['lastname']; ?>" />
                      Just a question.. is there a way to drop the state of the session when the submission is successful? I think it is session_destroy () but I will check into that.

                      I'm still working on the session errors. I can't seem to get them.

                      Comment

                      • pbmods
                        Recognized Expert Expert
                        • Apr 2007
                        • 5821

                        #12
                        Heya, Frank.

                        Originally posted by fjm
                        Just a question.. is there a way to drop the state of the session when the submission is successful? I think it is session_destroy () but I will check into that.
                        All you have to do is unset() your $_SESSION variables:

                        [code=php]
                        foreach(array(' firstname', 'lastname', 'age', 'err') as $key)
                        unset($_SESSION[$key]);
                        [/code]

                        This unsets $_SESSION['firstname'], $_SESSION['lastname'], $_SESSION['age'] and $_SESSION['err'].

                        Originally posted by fjm
                        I'm still working on the session errors. I can't seem to get them.
                        What I would do in this situation is to forget about output on test4.php. You want to do all your output in ro.php because that's where the User can actually do anything about the errors. If you output anything in test4.php, not only can you not redirect because you've already sent output to the browser, but you present the error messages on a blank page where the User can't do anything about them.

                        So let's change up test4.php. For line numbers, refer to the code in your last post.
                        • Remove lines 17-20. You'll output your errors on ro.php. Instead: [code=php]if(! empty($errors))
                          exit();[/code] This forces the browser to redirect to ro.php (since you already set the header), where it will display the errors.
                        • Add the following line after line 16: [code=php]$_SESSION['err'] = $errors;[/code]
                        • On line 27, instead of die(), set [code=php]$_SESSION['err'][] = mysql_error();
                          exit();[/code]
                        • On line 29, instead of echoing that a line was added, use $_SESSION['err'][] instead.


                        P.S. When posting source code, use [code=php] instead of [code] to specify PHP code so that we get pretty syntax coloring :)

                        Comment

                        • fjm
                          Contributor
                          • May 2007
                          • 348

                          #13
                          Hi pbmods! I;m back for another round today. :)

                          I did exactly what you suggested and even went as far as copying and pasting the code I left in the last post you told me to reference and I still get nothing.

                          Here is my code after your changes. I renamed the files to something easier. :)

                          1.php
                          [PHP]<?php
                          session_start() ;
                          $_SESSION['firstname'] = $_POST['firstname'];
                          $_SESSION['lastname'] = $_POST['lastname'];
                          $_SESSION['age'] = $_POST['age'];
                          //header( 'Location: 2.php' ) ;
                          include "persist.ph p";

                          $errors = array();
                          if (!$_POST['firstname'])
                          $errors[] = "First name is required";
                          if (!$_POST['lastname'])
                          $errors[] = "Last name is required";
                          if (!$_POST['age'])
                          $errors[] = "Age is required";

                          $_SESSION['err'] = $errors;

                          if(! empty($errors))
                          exit();
                          else {

                          $sql="INSERT INTO person (FirstName, LastName, Age)
                          VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
                          if (!mysql_query($ sql,$con))
                          {
                          $_SESSION['err'][] - mysql_error();
                          exit();
                          }
                          $_SESSION['err'][];

                          mysql_close($co n);
                          }
                          ?>[/PHP]

                          2.php
                          [PHP]<?php
                          session_start() ;
                          echo $_SESSION['err'];
                          ?>
                          <html>
                          <body>
                          <form method="post" name="submit" action="1.php">
                          Firstname: <input type="text" name="firstname " /><br />
                          Lastname: <input type="text" name="lastname" /><br />
                          Age: <input type="text" name="age" /><br />
                          <input name="submit" type="submit" />
                          </form></body>
                          </html>[/PHP]

                          Now, running this code gives me the following errors:
                          PHP Fatal error: Cannot use [] for reading in /var/www/eagleintl/1.php on line 28
                          I googled the error and it appears that there may be a bug in php with regard to line 28.

                          Also, you will see that I commented out the "header". The reason I did this was because I still wasn't getting the array to echo back to 2.php and wanted to see what was happening. Even if I put line 28 back to:

                          [PHP]die('Error: ' . mysql_error());[/PHP] it still won't work.

                          Any ideas?

                          Comment

                          • pbmods
                            Recognized Expert Expert
                            • Apr 2007
                            • 5821

                            #14
                            Heya, Frank. Welcome back!

                            On line 30 in the code you posted for 2.php, you have this statement:
                            [code=php]
                            $_SESSION['err'][];
                            [/code]

                            This is what should be causing your error. The '[]' operator is a special PHP construct that means, "Create a new numerical key in this array and assign it a value equal to the rhs (right-hand side)". The problem is, there's no rhs in that statement.

                            If you were to do this:

                            [code=php]
                            $_SESSION['err'][] = '1 row added successfully.';
                            [/code]

                            Then it would work because there is a valid rhs (the string, '1 row added successfully.') .

                            Comment

                            • fjm
                              Contributor
                              • May 2007
                              • 348

                              #15
                              Hmm.. Still no go.. I get this now:

                              Fatal error: Cannot use [] for reading in /var/www/eagleintl/1.php on line 27
                              I have the exact same code as posted above. Could it be my php settings?

                              Thanks for sticking with me pbmods.

                              Frank

                              Comment

                              Working...