Page 1 of 1

Noob post _SELF problems

Posted: Wed Sep 09, 2009 3:47 pm
by Shifty Geezer
Hi all,

Just starting out with php and wanting to create a dead-simple form that post to the same page. Gone through lots of tutes and examples and still can't get a proper working piece of code!

This is what I have, written in phpDesigner and running on WAMP

Code: Select all

<?php
if (!isset($_POST['Fname'])){
    $Fname = '';}
if (!isset($_POST['Lname'])){
    $Lname = '';}
if (!isset($_POST['submit'])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<input type="submit" value="submit" name="submit">
</form>
</body>
<?php
} else {
echo '<html>';
echo '<head>';
echo '<title>Personal INFO</title>';
echo '</head>';
echo '<body>';
 
echo "Hello, ".$Fname." ".$Lname.".<br />";
echo '</body>';
};
?>
I get 'undefined variable' errors for Fname and Lname after submitting. Replacing the second half with HTML code instead of php, from line 19 onwards...

Code: Select all

<?php
} else {
?>
<html>
<head>
<title>Personal INFO</title>
</head>
 
<body>
Hello, <?php echo $Fname?> <?php echo $Lname?>. It's lovely here.<br>
<?php
};
?>
I've been at this for a few days now. :banghead: I had the variables working at one point, but the Submit variable didn't. What an I doing wrong?!

Re: Noob post _SELF problems

Posted: Wed Sep 09, 2009 4:00 pm
by Eric!
That's an unusual way to spilt the if-then with in-line PHP. But your problem is you aren't reading your variables back properly. You need to extract them from $_POST

Change your echo to this and it will work (I only looked at the first set of php code)

Code: Select all

echo "Hello, ".$_POST['Fname']." ".$_POST['Lname'].".<br />";

Re: Noob post _SELF problems

Posted: Wed Sep 09, 2009 4:14 pm
by Shifty Geezer
Thank you! Thank you! Thank you! Now I realise what that $_POST[...] is all about. At last I 'get' php. :mrgreen:

The weird formatting came from trying to mix different approaches from different examples, and then work around the syntax errors. I'll go with a straight php, Echo, script from now on.

Re: Noob post _SELF problems

Posted: Wed Sep 09, 2009 4:26 pm
by Eric!
Yeah that's the magic. The form with method="post" tells the server to store the data so it can then be retrieved by a page (or _SELF) via $_POST.

For passing data between multiple pages $_SESSION is used. It's a bit more complicated, with session_start and stuff...

For passing data via the URL (all that ?junk=data&morejunk=moredata crap) is method="get" and then parsed via $_GET automatically in php.