473,397 Members | 1,985 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

How to post data to the same page

348 100+
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:

Expand|Select|Wrap|Line Numbers
  1.  <html>
  2. <body>
  3. <form action="test.php" method="post">
  4. Firstname: <input type="text" name="firstname" />
  5. Lastname: <input type="text" name="lastname" />
  6. Age: <input type="text" name="age" />
  7. <input type="submit" />
  8. </form>
  9. </body>
  10. </html> 
and..

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include "connection.php";
  3. $sql="INSERT INTO person (FirstName, LastName, Age)
  4. VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
  5. if (!mysql_query($sql,$con))
  6. {
  7. die('Error: ' . mysql_error());
  8. }
  9. echo "1 record added";mysql_close($con)
  10. ?> 
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
Jun 23 '07 #1
22 24106
pbmods
5,821 Expert 4TB
Heya, 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:

Expand|Select|Wrap|Line Numbers
  1. if( ! (
  2.     empty($_POST['firstname']) ||
  3.     empty($_POST['lastname']) ||
  4.     empty($_POST['age'])
  5. )) {
  6.     include('connection.php');
  7.     $sql="INSERT INTO person . . .
  8. .
  9. .
  10. .
  11. } else {
  12. ?>
  13. <html>
  14. .
  15. .
  16. .
  17. <?php } ?>
  18.  
Jun 24 '07 #2
fjm
348 100+
H pbmods..


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

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. if (isset($_POST['submit'])) {
  3. include "persist.php";
  4. $sql="INSERT INTO person (FirstName, LastName, Age)
  5. VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
  6.  
  7. if (!mysql_query($sql,$con))
  8. {
  9. die('Error: ' . mysql_error());
  10. }
  11. echo "1 record added";
  12. }
  13.  
  14. mysql_close($con)
  15. ?>
  16. <html>
  17. <body>
  18. <form method="post" action="ro.php">
  19. Firstname: <input type="text" name="firstname" />
  20. Lastname: <input type="text" name="lastname" />
  21. Age: <input type="text" name="age" />
  22. <input name="submit" type="submit" />
  23. </form></body>
  24. </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.
Jun 24 '07 #3
pbmods
5,821 Expert 4TB
Heya, 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['messageOrWhatever'] 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.
Jun 24 '07 #4
fjm
348 100+
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?
Expand|Select|Wrap|Line Numbers
  1. <?php session_start(); 
  2. session_register ("submit"); 
  3. ?>
  4.  
When you get back to the form, you display $_SESSION['messageOrWhatever'] 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?
Jun 24 '07 #5
fjm
348 100+
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:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. //header( 'Location: ro.php' ) ;
  3. $errors = array();
  4. $page = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
  5. if (!$_POST['firstname'])
  6.      $errors[] = "First name is required";
  7. if (!$_POST['lastname'])
  8.      $errors[] = "Last name is required";
  9. if (!$_POST['age'])
  10.      $errors[] = "Age is required";
  11.  
  12. if (count($errors)>0){
  13.      echo "<strong>ERROR:<br>\n";
  14.      foreach($errors as $err)
  15.         echo "$err<br>\n";
  16. } else {
  17.          include "persist.php";
  18.          $sql="INSERT INTO person (FirstName, LastName, Age)
  19.          VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
  20.          if (!mysql_query($sql,$con))
  21.          {
  22.              die('Error: ' . mysql_error());
  23.          }
  24.          echo "1 record added";
  25.  
  26.          mysql_close($con);
  27. }
  28. ?>
  29. <?php
  30. ?>
  31.  
ro.php
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <body>
  3. <form method="post" name="submit" action="test4.php">
  4. Firstname: <input type="text" name="firstname" /><br />
  5. Lastname: <input type="text" name="lastname" /><br />
  6. Age: <input type="text" name="age" /><br />
  7. <input name="submit" type="submit" />
  8. </form></body>
  9. </html>
  10.  
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
Jun 24 '07 #6
pbmods
5,821 Expert 4TB
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:
Expand|Select|Wrap|Line Numbers
  1. foreach($_POST as $key => $val)
  2.     $_SESSION[$key] = $val;
  3.  
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['theVarThatYouWant'] as the value for each of your inputs:

Expand|Select|Wrap|Line Numbers
  1. Firstname: <input type="text" name="firstname" value="<?php echo $_SESSION['firstname']; ?>" /><br />
  2.  
and so on.

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

Expand|Select|Wrap|Line Numbers
  1. if(! empty($_SESSION['errors'])) {
  2.     print('<div class="errors">' . implode('<br />', $_SESSION['errors']) . '</div>');
  3.     unset($_SESSION['errors']);
  4. }
  5.  
If there are any errors, this will display them (with each one separated by a '<br />'), then flush the errors array.
Jun 24 '07 #7
fjm
348 100+
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
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3. //$_SESSION['firstname'] = $_POST['firstname'];
  4. foreach($_POST as $key => $val)
  5.     $_SESSION[$key] = $val;
  6.  
  7. header( 'Location: ro.php' ) ;
  8. include "persist.php";
  9.  
  10.    $errors = array();
  11.    $page = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
  12.    if (!$SESSION['firstname'])
  13.       $SESSION['errors'] = "First name is required";
  14.    if (!$SESSION['lastname'])
  15.       $SESSION['errors'] = "Last name is required";
  16.    if (!$SESSION['age'])
  17.       $SESSION['errors'] = "Age is required";
  18.  
  19.    if (count($errors)>0){
  20.       echo "<strong>ERROR:<br>\n";
  21.       foreach($errors as $err)
  22.         echo "$err<br>\n";
  23.    } else {
  24.  
  25.           $sql="INSERT INTO person (FirstName, LastName, Age)
  26.           VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
  27.           if (!mysql_query($sql,$con))
  28.           {
  29.               die('Error: ' . mysql_error());
  30.           }
  31.           echo "1 record added";
  32.  
  33.           mysql_close($con);
  34.    }
  35. ?>

ro.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3. echo $_SESSION['err'];
  4. ?>
  5. <html>
  6. <body>
  7. <form method="post" name="submit" action="test4.php">
  8. Firstname: <input type="text" name="firstname" /><br />
  9. Lastname: <input type="text" name="lastname" /><br />
  10. Age: <input type="text" name="age" /><br />
  11. <input name="submit" type="submit" />
  12. </form></body>
  13. </html>
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.
Jun 24 '07 #8
pbmods
5,821 Expert 4TB
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.

Expand|Select|Wrap|Line Numbers
  1. if(! empty($_SESSION['errors'])) {
  2.     print('<div class="errors">' . implode('<br />', $_SESSION['errors']) . '</div>');
  3.     unset($_SESSION['errors']);
  4. }
  5.  
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:
Expand|Select|Wrap|Line Numbers
  1. $_SESSION['errors'] = array(
  2.     'Message 1',
  3.     'Message 2',
  4.     'Message 3'
  5. );
  6.  
Then:
Expand|Select|Wrap|Line Numbers
  1. print(implode('<br />', $_SESSION['errors']));
  2.  
Outputs:
Expand|Select|Wrap|Line Numbers
  1. 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:
Expand|Select|Wrap|Line Numbers
  1. foreach($_POST as $key => $val)
  2.     $_SESSION[$key] = $val;
  3.  
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:

Expand|Select|Wrap|Line Numbers
  1. <input type="text" name="firstname" value="<?php echo $_SESSION['firstname']; ?>" />
  2.  
Jun 24 '07 #9
fjm
348 100+
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
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3. echo $_SESSION['err'];
  4. ?>
  5. <html>
  6. <body>
  7. <form method="post" name="submit" action="test4.php">
  8. Firstname: <input type="text" name="firstname" /><br />
  9. Lastname: <input type="text" name="lastname" /><br />
  10. Age: <input type="text" name="age" /><br />
  11. <input name="submit" type="submit" />
  12. </form></body>
  13. </html>
  14.  
test4.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3. $_SESSION['firstname'] = $_POST['firstname'];
  4. $_SESSION['lastname'] = $_POST['lastname'];
  5. $_SESSION['age'] = $_POST['age'];
  6. header( 'Location: ro.php' ) ;
  7. include "persist.php";
  8.  
  9.    $errors = array();
  10.    if (!$_POST['firstname'])
  11.       $errors[] = "First name is required";
  12.    if (!$_POST['lastname'])
  13.       $errors[] = "Last name is required";
  14.    if (!$_POST['age'])
  15.       $errors[] = "Age is required";
  16.  
  17.    if (count($errors)>0){
  18.       echo "<strong>ERROR:<br>\n";
  19.       foreach($errors as $_SESSION['err'])
  20.         echo "$err<br>\n";
  21.    } else {
  22.  
  23.           $sql="INSERT INTO person (FirstName, LastName, Age)
  24.           VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
  25.           if (!mysql_query($sql,$con))
  26.           {
  27.               die('Error: ' . mysql_error());
  28.           }
  29.           echo "1 record added";
  30.  
  31.           mysql_close($con);
  32.    }
  33. ?>
  34.  
All I did was to set the $_SESSION in test4.php in the last line of the arrray. Is this ok and correct?
Jun 24 '07 #10
fjm
348 100+
Wow. Pbmods. I now see exactly what the line you provided does. It maintains state. :) I'm understanding a little more. Thank you!!
Expand|Select|Wrap|Line Numbers
  1. <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.
Jun 24 '07 #11
pbmods
5,821 Expert 4TB
Heya, Frank.

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:

Expand|Select|Wrap|Line Numbers
  1. foreach(array('firstname', 'lastname', 'age', 'err') as $key)
  2.     unset($_SESSION[$key]);
  3.  
This unsets $_SESSION['firstname'], $_SESSION['lastname'], $_SESSION['age'] and $_SESSION['err'].

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:
    Expand|Select|Wrap|Line Numbers
    1. if(! empty($errors))
    2.     exit();
    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:
    Expand|Select|Wrap|Line Numbers
    1. $_SESSION['err'] = $errors;
  • On line 27, instead of die(), set
    Expand|Select|Wrap|Line Numbers
    1. $_SESSION['err'][] = mysql_error();
    2. exit();
  • 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 :)
Jun 24 '07 #12
fjm
348 100+
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.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";

$_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($con);
}
?>[/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?
Jun 24 '07 #13
pbmods
5,821 Expert 4TB
Heya, Frank. Welcome back!

On line 30 in the code you posted for 2.php, you have this statement:
Expand|Select|Wrap|Line Numbers
  1.  $_SESSION['err'][];
  2.  
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:

Expand|Select|Wrap|Line Numbers
  1. $_SESSION['err'][] = '1 row added successfully.';
  2.  
Then it would work because there is a valid rhs (the string, '1 row added successfully.').
Jun 24 '07 #14
fjm
348 100+
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
Jun 24 '07 #15
pbmods
5,821 Expert 4TB
Hm.

Oh wait.

$_SESSION['err'][] - mysql_error();

Looks like a typo. Should be:

$_SESSION['err'][] = mysql_error();

instead.

(didn't use CODE tags so that it would be easier to see the difference)
Jun 24 '07 #16
fjm
348 100+
Hey pbmods.. You were right, that is what was making it crash. It no longer crashes but I still don't have the array echoing.

What I do see is the word "Array" and thats it. Hmmm.. If only we could just get the error message to echo in place of the 'Array" we would be set. :)

Thanks again!!
Jun 24 '07 #17
pbmods
5,821 Expert 4TB
Heya, Frank.

Ok. You're getting 'Array' because you're trying to print() an array. Not too useful, unfortunately.

Looking at this line in the (newly-renamed) 2.php:
Expand|Select|Wrap|Line Numbers
  1. echo $_SESSION['err'];
Change it to something like this:
Expand|Select|Wrap|Line Numbers
  1. foreach($_SESSION['err'] as $error)
  2.     echo $error . '<br />';
  3.  
Thanks for sticking with me pbmods.
No, thank you! 1000 posts, here I come!

Plus, I'm having fun :)
Jun 24 '07 #18
fjm
348 100+
Change it to something like this:
Expand|Select|Wrap|Line Numbers
  1. foreach($_SESSION['err'] as $error)
  2. echo $error . '<br />';
  3.  
Well now your on to something here Mr. pbmods. :) I *now* have the errors echoing to the screen on 2.php which is what we want. However, one sllllliiiiiite little thing that I noticed is that when you surf to that page, we immediately get "First name is required", "Last name is required" and "Age is required"

Now.... if I have learned anything at all through this *gruling* experience is that we may need a conditional statement to go around:

[PHP]foreach($_SESSION['err'] as $error)
echo $error . '<br />';[/PHP]

Am I correct? I will try it anyway cuz I think I am right. :)

No, thank you! 1000 posts, here I come!

Plus, I'm having fun :)
LOL!! Your a masichist, like me. :)

BTW: After 1000 posts, do you get a free toaster? haha
Jun 24 '07 #19
fjm
348 100+
Hey pbmods...

Question. Actually, if you wouldn't mind clarifying this for me.

What I have done is to use session_unset() after the

[PHP] SESSION['err'][/PHP] variable and that unsets the data once it has been entered into the database. I never did use a conditional statement as I thought I would need.

When I used session_unset(), I noticed that when I go to the php page (page1.php) I no longer see the error messages appearing *immediatley* and was wondering why. Could you please provide an explanation for this? I am trying to understand the new code.

Thanks,

Frank
Jun 25 '07 #20
pbmods
5,821 Expert 4TB
Heya, Frank.

You'll want to unset $_SESSION['err'] after you echo its contents in 2.php. Once you display your messages, they are no longer useful, and in fact they become a liability (as you are noticing because error messages aren't going away!).

But you *only* want to unset $_SESSION['err'] at that point. If you do it anywhere else, you're going to notice some odd behavior.

For example, if you were to do it here in 1.php:

Expand|Select|Wrap|Line Numbers
  1. if(! empty($errors))
  2.     exit();
  3.      else {
  4.  
  5.          $sql="INSERT INTO person (FirstName, LastName, Age)
  6.          VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
  7.          if (!mysql_query($sql,$con))
  8.          {
  9.              $_SESSION['err'][] = mysql_error();
  10.              exit();
  11.          }
  12.  
  13.          // What happens if we try this instead?
  14.          unset($_SESSION['err']);
  15.  
  16.          mysql_close($con);
  17. }
  18.  
Now, you have two problems. The first problem is that there will be *no* message on success (no feedback = bad). To illustrate the second problem, try this:
  • Try to pass an empty lastname. $_SESSION['err'] looks like this:
    • Last name is required.
  • Now enter a proper lastname, but try to pass an empty firstname. Because we never unset $_SESSION['err'], we now get this:
    • Last name is required.
    • First name is required.
    even though we *did* enter a valid lastname this time.

And so on.

The correct way to do this in 2.php:

Expand|Select|Wrap|Line Numbers
  1. foreach($_SESSION['err'] as $err)
  2.     echo $err . '<br />';
  3. // Flush error messages.
  4. unset($_SESSION['err']);
  5.  
Jun 25 '07 #21
fjm
348 100+
Hi pbmods,


Your right. It does produce odd behavior. Let me ask you a question. I don't really recall why I wanted to split the script into two. I did find another script that I have playing around with. It has the validation contained in the same script.

Is it benificial to have 2 scripts versus one? With one, I don't think I would need to use sessions, although the experience with sessions is invaluable for future things.

Thanks,

Frank
Jun 26 '07 #22
pbmods
5,821 Expert 4TB
Heya, Frank.

I don't really recall why I wanted to split the script into two. I did find another script that I have playing around with. It has the validation contained in the same script.

Is it benificial to have 2 scripts versus one?
The major advantage to keeping your database code and your display code separate is to avoid problems when the User refreshes the page.

With one, I don't think I would need to use sessions, although the experience with sessions is invaluable for future things.
Indeed, you are right. Getting comfortable with managing a $_SESSION is a very valuable skill; it grants your code a degree of freedom from the browser (since you're now storing variables directly on the server instead of passing them back and forth to the client), and it helps secure your site from hackers (since $_SESSION variables are 99.9% of the time completely inaccessible to non-administrators).
Jun 26 '07 #23

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: brendan | last post by:
Sorry this isnt a cross post .. i just didnt get any help from alt.php. I have a website which utilises post forms for navigation in some areas. Problem is, when *some* users hit the BACK button...
2
by: luu duong | last post by:
I know this is probably easy but here is the details. I have an asp page that is not inside a frameset. I want to post data to another asp page that is inside a frameset. So firstpage.asp has...
1
by: Mad Scientist Jr | last post by:
How do you get a ASP.NET page to return nothing, so the page posting form data to it doesn't reload? I have tried all combinations of the following: Response.SuppressContent = True...
0
by: Glen | last post by:
Is there any way to post data to an ASP.Net form and then display the page to the user with the posted data from a client app? Here's what I'm trying to do: Serialize a business object (order)...
15
by: tmax | last post by:
PHP Pros: I have a simple html form that submits data to a php script, which processes it, and then redisplays the same page, but with a "thank you" message in place of the html form. This is...
3
by: Yourself | last post by:
Hi, I'm trying to post data to PayPal for a shopping cart, basically I want to replicate a form like the following, but create the variables dynamically from code behind: <form...
4
by: David Veeneman | last post by:
I want to programmatically create some POST data on a web server, then pass that data to another web page that the server calls, using Server.Transfer(). What's the best way to do that? I'm...
4
by: dac | last post by:
I am quietly going insane on this project. I've never worked on a project like this one before. All my previous sticky forms were for data entry, not editing. I don't know how to display the form...
0
by: thirunavukarasukm | last post by:
Hai,, i want to post data with screen scrap page.. i want to send from to destination station which class and date... i run the screenscrap.aspx page the posted data send to the request...
1
by: JohnathanKong | last post by:
Hello, I hope this is the right place to post, but anyways, here goes. I current have a forum, snitz, in place, but am having an IE specific problem. Basically what happens is, I have a page that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.