New here and to php. I wrote a code to toggle between two images and changing a letter to two colors when two buttons are pressed. It is working but I keep getting the following error messages:
Warning: Undefined array key "button2" in C:xampphtdocsphpcoursepractice3.php on line 11 (Shows when button1 is clicked)
Warning: Undefined array key "button1" in C:xampphtdocsphpcoursepractice3.php on line 10 (Shows when button2 is clicked)
Any help on how to resolve this?? Below is my code:
<?php
$btn1='';
$btn2='';
$result = "img.png";
$style= "blue";
if($_SERVER['REQUEST_METHOD']==='POST'){
$btn1 = $_POST['button1'];
$btn2 = $_POST['button2'];
if(isset($btn1)){
$result = "img.png";
$style = "blue";
}
else {
$result = "img2.png";
$style = "red";
}
}
?>
<?php include "head.php"
?>
<body>
<form action="" method="post">
<button type="submit" name="button1">Button 1</button>
<button type="submit" name="button2">Button 2</button>
</form>
<img src="<?php echo $result ?>">
<h2 style="color:<?php echo $style?>">B</h2>
</body>
</html>
Tried everything to no avail.
2
Answers
You have two submit buttons in your form. When you click a button the browser will post a value for that button only. No value will be posted for the other button. Thus, your
$_POST
array doesn’t include a key for the second button. It makes no difference which button you click: the other button will be omitted.The way to test for a specific button is to use
if isset()
.For example:
For your code try
Only the button that’s used to submit the form gets sent to the server. So when you use button1,
$_POST['button2']
is undefined.Use the same name for your submit buttons, and distinguish them by value instead of by name.