I've simplified it for this question. But all I need to do is show a different result if a combination of buttons is checked. At the moment if Rice and Tea are checked there are no results.
<?PHP
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['food']."|".$_POST['drink'];
if ($selected_radio == 'rice' && 'tea') {
print '<h1>Rice and tea</h1>';
}
else if ($selected_radio == 'beans' && 'coffee') {
print '<h1>Beans and coffee</h1>';
}
}
?>
<form name ="form1" method ="POST" action =" ">
<p><input type = 'Radio' Name ='food' value= 'rice'>Rice</p>
<p><input type = 'Radio' Name ='food' value= 'beans'>Beans</p>
<p><input type = 'Radio' Name ='drink' value= 'tea'>Tea</p>
<p><input type = 'Radio' Name ='drink' value= 'coffee'>Coffee</p>
<input type = "Submit" Name = "Submit1" value = "Select">
</form>
(Apologies for asking a similar question earlier)
Update if condition
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['food']."|".$_POST['drink'];
if ($selected_radio == 'rice|tea') {
print '<h1>Rice and tea</h1>';
}
else if ($selected_radio == 'beans|coffee') {
print '<h1>Beans and coffee</h1>';
}
}
Change the condition of your if:
if (strpos($selected_radio, 'rice') !== FALSE && strpos($selected_radio, 'tea') !== FALSE) {
print '<h1>Rice and tea</h1>';
}
else if (strpos($selected_radio, 'beans') !== FALSE && strpos($selected_radio, 'coffee') !== FALSE) {
print '<h1>Beans and coffee</h1>';
}
(It's just a suggestion and I don't tested it ;))
Use this code:
$selected_radio_list = [
'rice|tea' => 'foo',
'beans|coffee' =>'bar'
];
$post = $_POST['food']. "|" .$_POST['drink'];
if(in_array($post, $selected_radio_list )){
echo $selected_radio_list[$post];
}
Related
I am trying to know which radio button is clicked by PHP in a form with $_POST['...'].
This is my form:
<form action="" method="post" enctype="multipart/form-data">
<div class="input-group">
<span class="input-group-addon">Add:</span>
<input type='radio' name='add1' id='program' value='program' onchange="hideCollege()" checked> Program Intern</input>
<input type='radio' name='add1' id='department_coop' value='department_coop' onchange="showCollegelist()"> Department Cooperation</input>
<input type='radio' name='add1' id='foreigner' value='foreigner' onchange="hideCollege()"> Foreigner Area</input>
</div>
</form>
And I am trying to receive the values of the three radio buttons by:
if(isset($_POST['program'])){
$program = 1;
}
else if(isset($_POST['foreigner'])){
$foreigner = 1;
}
else if(isset($_POST['department_coop'])){
$coop = 1;
$college = $_POST['college'];
$department = $_POST['department'];
}
But it seems that no if statements are true, and turns out that no variables are assigned value. Does anyone know how to get to what I aim to do? Thanks a lot in advance.
Try this below section . Post request value should processed on form name attributes. So must check the conditional form post name value.
if(isset($_POST['add1']) && $_POST['add1']=='program' ){
$program = 1;
}
else if(isset($_POST['add1']) && $_POST['add1']=='foreigner' ){
$foreigner = 1;
}
else if(isset($_POST['add1']) && $_POST['add1']=='department_coop' ){
$coop = 1;
$college = $_POST['college'];
$department = $_POST['department'];
}
You should check the values of the radio button on the basis of name attribute.
if(isset($_POST['add1']) && $_POST['add1']=='program'){
$program = 1;
}
else if(isset($_POST['add1']) && $_POST['add1']=='foreigner'){
$foreigner = 1;
}
else if(isset($_POST['add1']) && $_POST['add1']=='department_coop'){
$coop = 1;
$college = $_POST['college'];
$department = $_POST['department'];
}
Then you will get the checked value.
If you access $_POST['add1'] check for the value as it should either be program, department_coop or foreigner (in this case)
I'm making a form where i have to insert in my dB several values from a checkbox btn group into different columns. I also have to insert two different values depending if the btn is checked or not.
I made it work in the following way, but is there another way for this became more simple? It´s a lot of issets :).
Thanks for your time.
Best regards!
NM
<?php
if(isset($_POST["submit"])){
// Create connection
include ('connection.php');
if(isset($_POST['fixvalue']) && ($_POST['fixvalue'] == 0)) {
$fixvalue= "fixvalue";
} else {
$fixvalue= 0;
};
if(isset($_POST['frtvalue']) && ($_POST['frtvalue'] == 0)) {
$valueone= "valueone";
} else {
$valueone= 0;
};
if(isset($_POST['secvalue']) && ($_POST['secvalue'] == 0)) {
$valuetwo= "valuetwo";
} else {
$valuetwo= 0;
};
if(isset($_POST['thevalue']) && ($_POST['thevalue'] == 0)) {
$valuethree= "valuethree";
} else {
$valuethree= 0;
};
if(isset($_POST['fovalue']) && ($_POST['fovalue'] == 0)) {
$valuefour= "valuefour";
} else {
$valuefour= 0;
};
if(isset($_POST['fitvalue']) && ($_POST['fitvalue'] == 0)) {
$valuefive= "valuefive";
} else {
$valuefive= 0;
};
$sql = "INSERT INTO values(fixvalue,valueone,valuetwo,
valuethree,valuefour,valuefive)
VALUES('".$fixvalue."','".$valueone."','".$valuetwo."',
'".$valuethree."','".$valuefour."','".$valuefive."')";
if ($con->query($sql) === TRUE) {
echo'<button class="btn btn-success" style="left:400px;bottom:20px;width:200px;">Sucess</button>';
echo "<script type= 'text/javascript'>alert('New record OK');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" $con->error."');</script>";
}
$con->close();
}
?>
Here's what I would do:
<form action="" method="post">
<input type="checkbox" name="fixvalue"> Checkbox<br>
<input type="checkbox" name="valueone"> Checkbox 1<br>
<input type="checkbox" name="valuetwo"> Checkbox 2<br>
<input type="checkbox" name="valuethree"> Checkbox 3<br>
<input type="checkbox" name="valuefour"> Checkbox 4<br>
<input type="checkbox" name="valuefive"> Checkbox 5<br>
<input type="submit" name="submit">
</form>
<?php
$fields = [
'fixvalue' => 0,
'valueone' => 0,
'valuetwo' => 0,
'valuethree' => 0,
'valuefour' => 0,
'valuefive' => 0
];
if($_POST['submit']){
foreach($_POST as $key => $value) {
if($key !== 'submit') {
$fields[$key] = $key;
}
}
extract($fields);
$sql = $db->prepare("INSERT INTO table_name (fixvalue, valueone, valuetwo, valuethree, valuefour, valuefive) VALUES(:fixvalue, :valueone, :valuetwo, :valuethree, :valuefour, :valuefive)");
foreach ($fields as $key => $value) {
$sql->bindValue(':'.$key, $$value);
}
$sql->execute();
}
?>
$checks = array(
'fixvalue',
'frtvalue',
'secvalue',
'thevalue',
'fovalue',
'fitvalue'
);
$data = array();
foreach( $checks as $value){
$data[$value] = isset($_POST[$value]) && $_POST[$value] != '' ? $_POST[$value] : 0;
}
Than use $data['frtvalue'] etc in a prepared sql statement
When I check the checkbox there is no errors, but when I didn't check the checkbox it gives me errors.
<?php
if(isset($_REQUEST['btn']))
{
$remmber = $_REQUEST['active'];
if($remmber == "on")
{
echo "Checked";
}
else {$remmber = "";}
}
?>
<html>
<form name= "frm" action = "test.php" method = "post" >
<p>Username
<input type = "text" name = "name" value = "" />
</p>
<p>Password
<input type = "text" name = "password" value = "" />
</p>
<p>
<td colspan = "2"><input type = "checkbox" name = "active" value = "active" />Keep Me Loged In
</p>
<p><input type = "submit" name = "btn" value = "Login" />
</p>
</form>
</html>
For checkboxes if they are not checked then they are not posted. So check if it is present in the posted data then set on, else set blank to the variable. Try with -
if(isset($_REQUEST['btn']))
{
$remmber = !empty($_REQUEST['active']) ? 'on' : '';
if($remmber == "on")
{
echo "Checked";
}
else
$remmber = "";
}
if($remmber == "on") yet you're using and specifying a value value = "active"
"on" is the default value for a checkbox if a value is not specified.
Therefore, you need to adjust it to read as
if($remmber == "active")
Edit: (an explanation)
The reason why you're getting an undefined index, is that once you hit the submit submit and do not tick the checkbox, it will produce that notice.
Modify your code to read as and check if the checkbox value is set.
if(isset($_REQUEST['btn']))
{
if(isset($_REQUEST['active'])){
$remmber = $_REQUEST['active'];
if($remmber == "active")
{
echo "Checked";
}
else {$remmber = "";}
} // closing brace for if(isset($_REQUEST['active']))
}
Additional edit, to show the user that the checkbox isn't set:
if(isset($_REQUEST['btn']))
{
if(isset($_REQUEST['active'])){
$remmber = $_REQUEST['active'];
if($remmber == "active")
{
echo "Checked";
}
else {$remmber = "";}
} // closing brace for if(isset($_REQUEST['active']))
else{ echo "The checkbox was not ticked.";
}
}
Footnotes:
You should also use a conditional !empty() for your inputs.
You're only checking if the submit and checkbox are set.
After noticing a comment you left in another answer:
#Barmar i am just using this for login page , where i am using a checkbox to remember username and password. – Akshat Dhiman
Please read the following Q&A on Stack:
Remember me Cookie best practice?
It also contains valuable information regarding passwords.
I hope you are using modern-day hashing methods also, such as password_hash() as well as prepared statements.
you can use simply isset
if(isset($_REQUEST['btn']))
{
$remmber = isset($_REQUEST['active']) ? $_REQUEST['active'] : '';
if($remmber == "on")
{
echo "Checked";
}
else {$remmber = "";}
}
I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>
In my form I am trying to get the radio checked value to be passed on to the next page (which is an FPDF page)
I have 4 options: Annual Leave, Sick Leave, Business Leave, & also others with a textfield.
However I have tried a lot of 'if' as well as 'switch cases'
I am getting either only the element with value '1'
or else 'Undefined index: rad in D:\xampp\htdocs\Application\generate_report.php on line 13'
some where I am wrong, can anyone help me please. My code below.
html form:
<form id="formmain" method="post" action="generate_report.php" onsubmit="return_validate()">
<script type="text/javascript">
function selectRadio(n){
document.forms["form4"]["r1"][n].checked=true
}
</script>
<table width="689">
<tr>
<td width="500d">
<input type="radio" name="rad" value="0" />
<label>Business Trip</label>
<input type="radio" name="rad" value="1"/><label>Annual Leave</label>
<input type="radio" name="rad" value="2"/><label>Sick Leave</label>
<input type="radio" name="rad" value="3"/><label>Others</label> <input type="text" name="others" size="25" onclick="selectRadio(3)" />
</td>
</tr>
</table>
//....
//below submit button is end of the html page:
<input type="submit" name="submit" value="send" />
</form>
Generate PDF form:
$radio = $_POST['rad']; // I am storing variable
if($radio = 0) {
$type = 'Business Leave';
}elseif ($radio = 1) {
$type = 'Annual Leave';
}elseif ($radio = 2) {
$type = 'Sick Leave';
} else { $type = $_POST['others']; }
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
if($radio = 0)
and
elseif ($radio = 1)
and all the other elseifs have to be == 1, with two '='!
A further explanation on the OP. If you do not use == then you are setting the value, not checking it. Furthermore, there are levels of checking. Using the double equals (==) is effectively stating "is equal to" whereas using triple equals (===) is like stating "is absolutely equal to". Generally the == operator will do everything you need but sometimes when working with data types or specific values you might need ===. This is mostly FYI as the OP has an actionable solution.
You should always check if inputs are checked or any value inserted. If there's no value, then it throws an undefined index error. Also, you should replace =s to == in your if clauses. So:
PHP:
$radio = $_POST['rad']; // I am storing variable
if (isset($radio)) { // checks if radio is set
if($radio == 0) {
$type = 'Business Leave';
}elseif ($radio == 1) {
$type = 'Annual Leave';
}elseif ($radio == 2) {
$type = 'Sick Leave';
} else {
if (isset($_POST['others'])) { // cheks if input text is set
$type = $_POST['others'];
}
else {
echo 'Error';
}
}
//echo
$pdf->Cell(98,10, 'Reason | ' .$type , 1, 0, 'C', $fill);
}
else {
echo 'Error';
}
Now it should work.