A php 'if statement' example from a tutorial by Kevin Yank doesn't seem to work. Specifically, both branches of the conditional appear when the page loads. I have also tried changing to the non-shorthand 'if' syntax, to no avail. Is the problem something other than syntax?
The code is as follows:
<!DOCTYPE html>
<html>
<head>
<title> Sample Page </title>
</head>
<body>
<?php if(isset($name)) : ?>
<p> Your name: <?php echo ($name); ?> </p>
<p> This paragraph contains a <a href="goodone.php"> link</a> that passes the name variable on to the next document. </p>
<?php else : ?>
<!-- No name has been provided, so prompt the user for one -->
<form action="<php echo($PHP_SELF); ?>" method="get">
Please enter your user name:
<input type="text" name="name">
<input type="submit" value="ok">
</form>
<?php endif; ?>
</body>
</html>
This script left out a very important element >>> $name=$_GET['name'];
<<<
The name
must first be declared as a variable.
It has been added inside this line: <?php if(isset($name)) : ?>
See my code below: (tested and working)
<HTML>
<HEAD>
<TITLE> Sample Page </TITLE>
</HEAD>
<BODY>
<?php $name=$_GET['name']; if (isset($name)): ?>
<P>Your name: <?php echo($name); ?></P>
<P>This paragraph contains a
<A HREF="newpage.php?name=<?php echo(urlencode
($name)); ?>">link</A> that passes the
name variable on to the next document.</P>
<?php else: ?>
<!-- No name has been provided, so we
prompt the user for one. -->
<FORM ACTION="<?php echo($PHP_SELF); ?>" METHOD="GET">
Please enter your name: <INPUT TYPE="TEXT" NAME="name">
<INPUT TYPE="SUBMIT" VALUE="GO">
</FORM>
<?php endif; ?>
</BODY>
</HTML>
Plus as an added bonus (tested and working), you can use the PHP code below, inside your goodone.php
file to echo
the name after you clicked on the link after you submitted the form. You can do whatever you wish from hereonin, for database use, etc.
<?php
echo($_GET['name']);
// do something else
?>