Why deos it return 2 when I check both checkboxes? How can I return a different response when both checkboxes are turn on?
html:
<form action="form3.php" method="POST">
<fieldset>
<legend> select your team </legend>
<input type="checkbox" name="punto3" value="1"> 1 </input>
<input type="checkbox" name="punto3" value="2"> 2 </input>
<p><input type="submit"></p>
</fieldset>
</form>
php:
<?php
if (isset($_REQUEST['punto3']))
{
$punto3 = $_REQUEST['punto3'];
$conn = new mysqli("localhost", "root", "", "progetto2");
if ($conn == false)
{
die("fail: " . $conn->connect_error);
}
switch ($punto3)
{
case '1': // 1 checkbox
break;
case '2': // 2 checkbox
break;
default: // if 1 and 2 is both checked
}
} else {
echo "Please, do at least one selection";
}
?>
Any suggestion?
CodePudding user response:
Use separate name attribute values for each checkbox and use if conditions instead of a switch (or use the radio button if you have required only one value) example:
HTML:
<form action="form3.php" method="POST">
<fieldset>
<legend> select your team </legend>
<input type="checkbox" name="punto3_1" value="1"> 1 </input>
<input type="checkbox" name="punto3_2" value="2"> 2 </input>
<p><input type="submit"></p>
</fieldset>
</form>
PHP:
<?php
if (
(isset($_REQUEST['punto3_1']) && $_REQUEST['punto3_1'] != "")
|| (isset($_REQUEST['punto3_2']) && $_REQUEST['punto3_2'] != "")
)
{
$punto3_1 = $_REQUEST['punto3_1'];
$punto3_2 = $_REQUEST['punto3_2'];
$conn = new mysqli("localhost", "root", "", "progetto2");
if ($conn == false)
{
die("fail: " . $conn->connect_error);
}
if(isset($_REQUEST['punto3_1']) && $_REQUEST['punto3_1'] != ""){
//your logic for punto3_1 will goes here....
} elseif(isset($_REQUEST['punto3_2']) && $_REQUEST['punto3_2'] != ""){
//your logic for punto3_2 will goes here....
} else {
//your logic for punto3_1 and punto3_2 will goes here....
}
} else {
echo "Please, do at least one selection";
}
?>