How to check which radio button is clicked by PHP $_POST? - php

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)

Related

Update checkbox value in SQL table

I can display checkbox value from a SQL query, but I can't update them, I just can update untick value (0 value), if I untick the checkbox, it can save the untick value 0 to the SQL table. if I retick the checkbox, it cannot update the value in the SQL query. I'm using int as the data type. Here's the sample code from my test system:
Checkbox HTML:
<div class="form-group col-lg-6">
<label class="control-label col-lg-4">Pricing<span style="color:red;"> </span></label>
<div class="col-lg-8">
<input type="checkbox" name="rm_option" id="rm_option" value="1"><strong> RM </strong></input>
<input type="checkbox" name="point_option" id="point_option" value="1"><strong> Full Point </strong></input>
<input type="checkbox" name="partial_option" id="partial_option" value="1"><strong> Partial Point + RM </strong></input>
</div>
</div>
Checkbox echo edit function:
<?php
$sql = "select * from promotion_list where id=" . $_GET['id'];
$arr_sql = db_conn_select($sql);
foreach ($arr_sql as $rs_sql) {
foreach ($rs_sql as $key => $value) {
?>
$("#<?php echo $key ?>").val("<?php echo $value ?>");
<?php if($value == 1){ ?>
$("#<?php echo $key ?>").attr("checked", true).prop("checked", true);
<?php } ?>
<?php
}
?>
$("#filter_id").val('<?php echo $rs_sql['id'] ?>');
$("#promotion_content").jqteVal('<?php echo $rs_sql['promotion_content'] ?>');
$("#promotion_terms").jqteVal('<?php echo $rs_sql['promotion_terms'] ?>');
$("#promotion_instruction").jqteVal('<?php echo $rs_sql['promotion_instruction'] ?>');
$("#promotion_policy").jqteVal('<?php echo $rs_sql['promotion_policy'] ?>');
<?php
}
?>
Update function:
else if($action == 'update') {
$rm_option = isset($_POST['rm_option']) ? $_POST['rm_option'] : "";
$point_option = isset($_POST['point_option']) ? $_POST['point_option'] : "";
$partial_option = isset($_POST['partial_option']) ? $_POST['partial_option'] : "";
$query = "UPDATE " . $table ." SET id_promotion_categories = '" . $id_promotion_categories . "',
promotion_title = '".$promotion_title."',
rm = '".$rm."', promotion_description = '".$promotion_description."',
point = '".$point."', point_rm_point = '".$point_rm_point."', point_rm_rm = '".$point_rm_rm."',
quantity_limit_option = '".$quantity_limit_option."', quantity_limit = '".$quantity_limit."',
discount_percentage = '".$discount_percentage."', promotion_price_before = '".$promotion_price_before."',
promotion_price_after = '".$promotion_price_after."',
redemption_from_date = '".$redemption_from_date."', redemption_to_date = '".$redemption_to_date."',
rm_option = '".$rm_option."', point_option = '".$point_option."', partial_option = '".$partial_option."',
merchant_option = '".$merchant_option."', merchant_price = '".$merchant_price."',
reservation = '".$reservation."', feature = '".$feature."' where id='" . $id . "'";
$arr_treatment = db_conn_update($query);
if ($arr_treatment) {
$result_arr['msg'] = 'Update Successful';
} else {
$result_arr['msg'] = 'Error in processing data. Please try again later.';
}
$result_arr = special_char_display_arr($result_arr);
$json = json_encode($result_arr);
print($json);
}
Below is my output(It can not let me update in the empty checkbox, for example, Partial Point + RM in below):
All update record is no problem, only for the checkbox cannot update. I hope anyone can guide me solve this problem. Thanks a lot.
For checkboxes, the $_POST array element is present (and = 1) if the checkbox is checked, otherwise it is absent. So change
$rm_option = isset($_POST['rm_option']) ? $_POST['rm_option'] : "";
$point_option = isset($_POST['point_option']) ? $_POST['point_option'] : "";
$partial_option = isset($_POST['partial_option']) ? $_POST['partial_option'] : "";
to
$rm_option = isset($_POST['rm_option']) ? 1 : 0;
$point_option = isset($_POST['point_option']) ? 1 : 0;
$partial_option = isset($_POST['partial_option']) ? 1 : 0;
and you should be able to update 0 values as well. Note that as #SergheiLeonenco said, since these are numeric values, you don't need quotes around them in your query.
Mandatory SQL injection commentary.
Because you are using $_POST values directly in your query, you are vulnerable to SQL injection. You should read How can I prevent SQL injection in PHP and move to prepared statements to protect yourself.

Is checkboxes checked or not?

Need som serious help!
<?php
$php1 = !isset($_GET['php1']);
$php2 = !isset($_GET['php2']);
$php3 = !isset($_GET['php3']);
$php4 = !isset($_GET['php4']);
$php5 = !isset($_GET['php5']);
if ($php1 == 'one' && $php2 == 'two' && $php5 == 'five') {
echo "<h2>R</h2>WRONG";
} else {
echo "<h2>R</h2>CORRECT";
}
?>
HTML
<form action="One.php" method="get">
<input type="checkbox" name="php1" value="one"> q1<br>
<input type="checkbox" name="php2" value="two"> q1<br>
<input type="checkbox" name="php3" value="three"> q1<br>
<input type="checkbox" name="php4" value="four"> q1<br>
<input type="checkbox" name="php5" value="five"> q1<br>
<br>
<input type="submit" value="Send!">
</form>
If all checkboxes are empty, there will be a message saying that. How do I do it?
If I dont check any boxes, it tells me the answers are correct. That's wrong.
<?php
If(isset($_GET['php1'])){
$php1 = 1;
}else{
$php1 = 0;
}
If(isset($_GET['php2'])){
$php2 = 1;
}else{
$php2 = 0;
}
If(isset($_GET['php3'])){
$php3 = 1;
}else{
$php3 = 0;
}
If(isset($_GET['php4'])){
$php4 = 1;
}else{
$php4 = 0;
}
If(isset($_GET['php5'])){
$php5 = 1;
}else{
$php5 = 0;
}
if ($php1 && $php2 && $php5) {
echo "<h2>Resultat</h2>Du svarade rätt på frågan";
} else {
echo "<h2>Resultat</h2>Du svarade fel på frågan";
}
Try this.
Each php variable will have the value of 1 or 0 (true/false). Thus the if only needs to check it if it is or not.
You have to remember that UN-CHECKED Checkboxes are not even sent to the PHP script $_POST/$_GET by the browser.
So there existance is normally all you need to know.
First you must check that they were passed to the script and then check its value, otherwise you will receive undefined index errors for each checkbox that was not checked by the user
if (isset($_GET['php1']) && $_GET['php1'] != '' ) {
Although as the checkbox called php1 can only be set to the value you give it, its value can be assumed and all you need to do is
if (isset($_GET['php1']) ) {
// php1 was checked
Also isset() will test more than one variable exists using an AND. So you could write your code as
if ( isset($_GET['php1'], $_GET['php2'], $_GET['php5']) ) {
echo "<h2>Resultat</h2>Du svarade rätt på frågan";
} else {
echo "<h2>Resultat</h2>Du svarade fel på frågan";
}
$php1 = !isset($_GET['php1']);
This means $php1 is either true or false. If you want the value of php1 get parameter then remove isset cover, just
$_GET['php1'];
isset is used to check whether the variable exist or not after that use $_GET['php1'];

Codeigniter - Edit Form with Checkbox

I'm using codeigniter and have a problem with my edit form in checkbox. The checkbox have 2 values 1 and 0, if checked then the value is 1 and if unchecked then the value is 0.
here is my controller:
function updatepost($id=0){
$data = $_POST;
$this->db->where('id_post',$id);
$outp = $this->db->update('post',$data);
}
And here is my view
sport <input type="checkbox" name="sport" value="1" <?php if($data['sport'] == '1'){echo 'checked';}?> />
tekno <input type="checkbox" name="tekno" value="1" <?php if($data['tekno'] == '1'){echo 'checked';}?>/>
game <input type="checkbox" name="game" value="1" <?php if($data['game'] == '1'){echo 'checked';}?>/>
if i unchecked the checkbox, value should be '0';
My question is how to get value if the checkbox is uncheked?
Many thanks for the answer..
Checkboxes are posted only if they are checked.
In your controller, check if they are posted,
if posted, value is 1 else 0.
Example Code:
$sport = 0;
if (! empty($_POST['sport']) {
$sport = 1;
}
If you want to use ternary operators, use:
$sport = (! empty($_POST['sport']) ? 1 : 0;
So, final code:
function updatepost($id=0){
// Assign default values in view that they are not getting
// posted if they are not checked.
// If they are posted, they will be overriden in $data.
$data['sport'] = $data['tekno'] = $data['tekno'] = 0;
$data = $_POST;
$this->db->where('id_post',$id);
$outp = $this->db->update('post',$data);
}
In your controller file replace the $data = $_POST; line by the following code
$data['sport'] = (array_key_exists('sport',$_POST)) ? $_POST['sport'] : 0;
$data['tekno'] = (array_key_exists('tekno',$_POST)) ? $_POST['tekno'] : 0;
$data['game'] = (array_key_exists('game',$_POST)) ? $_POST['game'] : 0;

Passing information using post method without session variables

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>

Is there a way of updating a large form with checkboxes effectively?

Having an issue updating a large form with checkboxes effectively to database.
Just for illustration:
<form action="save.php" method="post">
<?php
for {$i=0;$i<1000;$i++) {
echo '<input type="checkbox" name="product-' . $i . '">';
}
<input type="submit">
</form>
<?php
$posted_values = $_POST;
foreach($posted_values as $key=>$p) {
$chkbox = $posted_values[$p];
$update = 0;
if ($chkbox == 'on') {
$update = 1;
}
//Do some "expensive" checking for each posted value
$save_dbarray[$key] = $update;
}
//Do the actual updating to databased based on array `save_dbarray`
Is there any way of just adding changed checkboxes to the save_dbarray? (Only checked boxes would be posted to $_POST, but I want unchecked values to be a part of the update as well if they have changed) I have to do some expensive checking for each posted value, therefore
UPDATE
I dont want to have loop through all 1000 checkboxes. I just want to loop through the changed (from checked to unchecked or from unchecked to checked) checkboxes, but in above case $posted_values would only return checkboxes that has checked values (from unchecked to checked)
<?php
//I DONT want to have to do like this:
for {$i=0;$i<1000;$i++) {
$prodnr = 'product-' . $i;
$chkbox = $_POST[$prodnr];
$update = 0;
if ($chkbox == 'on') {
$update = 1;
}
//Do some "expensive" checking for every value
$save_dbarray[$key] = $update;
}
//Do the actual updating to databased based on array `save_dbarray`
You can use HTML array inputs and PHP to do the same.
A sample code will be like below.
<form action="save.php" method="post">
<?php
for ($i=0;$i<1000;$i++) {
echo '<input type="checkbox" name="products[]" value="' . $i . '"> '. $i .'<br>';
}
?>
<input type="submit">
</form>
<?php
print_r($_POST['products']); // Will contain your desired output
foreach($_POST['products'] as $i) {
$save_dbarray[$i] = 'on'; // 'on' or whatever value if you need.
// Actually you just need $_POST['products'], no need for this loop.
}
print_r($save_dbarray);
?>
EDIT
You need to loop through $_POST['products'] to find the new checked ones and you need to loop through $already_selected to find the unchecked ones.
<?php
// Select from db or something
$already_selected = array(2,3);
foreach($_POST['products'] as $i) {
if(!in_array($i,$already_selected)){
$save_dbarray[$i] = 'checked_update';
}
}
foreach($already_selected as $j) {
if(!in_array($j,$_POST['products'])){
$save_dbarray[$j] = 'unchecked_update';
}
}
print_r($save_dbarray);
// Do db update and select again and update $already_selected to display the checked ones
?>
<form action="save.php" method="post">
<?php
for ($i=1;$i<10;$i++) {
$checked = in_array($i, $already_selected) ? 'checked' : '';
echo '<input type="checkbox" name="products[]" value="' . $i . '" ' . $checked . '> '. $i .'<br>';
}
?>
<input type="submit">
</form>

Categories