Nickool
Nickool

Reputation: 3702

post an array to webpage

it has error because $_POST['sub1'] can't be accessed is there any approach or solution to echo the value of $_POST['sub1']? or impossible? no way? even with another arrays? i had question about my code nobody solved it! then I decide to tell it in simple way.

<html>
<form method="post">
<input type='submit' name='sub1' value='sub1'>
<?php
if(array_key_exists('sub1',$_POST))
{
echo"<input type='submit' name='sub2' value='sub2'>";
}
if(array_key_exists('sub2',$_POST))
{
echo $_POST['sub1'];
}
?>
</form>
</html>

Upvotes: 0

Views: 92

Answers (2)

Halcyon
Halcyon

Reputation: 57729

I think I know what is wrong here.

When you submit the form the second time (for sub2) you are no longer posting the value of sub1 along with it, just sub2.

This should fix it:

<html>
<form method="post">
<input type='submit' name='sub1' value='sub1'>
<?php
if(array_key_exists('sub1',$_POST))
{
echo"<input type='hidden' name='sub1' value='" . htmlentities($_POST['sub1']) . "'>";
echo"<input type='submit' name='sub2' value='sub2'>";
}
if(array_key_exists('sub2',$_POST))
{
echo $_POST['sub1'];
}
?>
</form>
</html>

Upvotes: 1

Marc B
Marc B

Reputation: 360702

You're using submit buttons. Only the button that you actually click will have its name/value pair sent to the server. When you click the sub2 button, only sub2=sub2 is sent, so sub1 won't exist in the $_POST array.


followup:

$_POST is created for you by PHP based on what's sent from the browser. The way you've built your form makes it impossible for 'sub1' to exist when you click the 'sub2' button. In other words, you need to use the SAME name= for BOTH buttons, and change the value= as appropriate:

html:

<input type="submit" name="submit" value="sub1" />
<input type="submit" name="submit" value="sub2" />

php:

if (isset($_POST['submit'])) {
   echo "You clicked the {$_POST['submit']} button";
}

Upvotes: 1

Related Questions