PHP session echo checkbox and radio buttons - php

I am trying to echo checkbox names, however I am unable to echo the name of the checkbox as all that appears is a '1' if the checkbox or radio button has been checked.
Does anyone know how I can change my code so that if the user selects that they are a vegetarian and allergic to peanut, "Vegetarian, Peanut Allergy" is displayed on my page instead of the number "1" for each checked item.
I would also prefer the cost of sitting in the VIP area to be echoed as apposed to "Yes" or "No".
Here is my the relevant code for the checkboxes and radio buttons on my reservations page:
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['vege'] = isset($_POST['vege']);
}
if (isset($_POST['submit'])) {
$_SESSION['vegan'] = isset($_POST['vegan']);
}
if (isset($_POST['submit'])) {
$_SESSION['peanut'] = isset($_POST['peanut']);
}
if (isset($_POST['submit'])) {
$_SESSION['gluten'] = isset($_POST['gluten']);
}
if (isset($_POST['submit'])) {
$_SESSION['vip'] = isset($_POST['vip']);
}
?>
...
<strong>Dietary Requirements:</strong>
Vegetarian <input type="checkbox" name="vege" value="Vegetarian" <?php if(isset($_POST['vege'])) echo "checked='checked'"; ?>>
Vegan <input type="checkbox" name="vegan" value="Vegan" <?php if(isset($_POST['vegan'])) echo "checked='checked'"; ?>>
Peanut Allergy <input type="checkbox" name="peanut" value="Peanut Allergy" <?php if(isset($_POST['peanut'])) echo "checked='checked'"; ?>>
Gluten Allergy <input type="checkbox" name="gluten" value="Gluten Allergy" <?php if(isset($_POST['gluten'])) echo "checked='checked'"; ?>>
<strong> VIP area* : </strong> <br><br>
Yes (+£5) <input type="radio" name="vip" <?php if (isset($vip) && $vip=="Yes") echo "checked";?> value="Yes">
<br><span id="vip" class="error"><?php echo $vipErr;?></span><br>
No <input type="radio" name="vip" <?php if (isset($vip) && $vip=="No") echo "checked";?> value="No">
Here is the php I am currently using which echos "1" when the user makes a selection on my thank you page:
<b>Dietary Requirements: </b><?php echo $_SESSION['vege'];?><?php echo $_SESSION['vegan'];?><?php echo $_SESSION['peanut'];?><?php echo $_SESSION['gluten'];?>
<b>VIP Area Costs: </b>£<?php echo $_SESSION['vip'];?>

You assigned not the value to the session array! Because you used isset() as a assignment! And then you assigned 1 because isset returned 1, because they are set!
So try this:
<?php
session_start();
if ( !empty($_POST['vege']) )
$_SESSION['vege'] = $_POST['vege'];
if ( !empty($_POST['vegan']))
$_SESSION['vegan'] = $_POST['vegan'];
if ( !empty($_POST['peanut']))
$_SESSION['peanut'] = $_POST['peanut'];
if ( !empty($_POST['gluten']))
$_SESSION['gluten'] = $_POST['gluten'];
if ( !empty($_POST['vip']))
$_SESSION['vip'] = $_POST['vip'];
?>
Edit:
If you echo session index check if they are set like this:
<b>Dietary Requirements: </b>
<?php
if(isset($_SESSION['vege']))
echo $_SESSION['vege'];
if(isset($_SESSION['vegan']))
echo $_SESSION['vegan'];
if(isset($_SESSION['peanut']))
echo $_SESSION['peanut'];
if(isset($_SESSION['gluten']))
echo $_SESSION['gluten'];
?>
<b>VIP Area Costs: </b>£<?php if(isset($_SESSION['vip'])) echo $_SESSION['vip'];?>

Basically your error is displaying boolean from isset() function.
if you want to echo value just use
$_SESSION['vegan'] = isset($_POST['vegan']) ? $_POST['vegan']:"";
what does the code mean?
$x = $trueOrFalse ? $valueIfTrue : $valueIfFalse;
of course perform some sanitizing:
$_SESSION['vegan'] = htmlspecialchars($_POST['vegan']);
NEVER EVER ECHO PURE USER INPUT! Always sanitize! By not sanitizing user input you allow custom external scripts to easily be run as any HTML tag can be injected into the page such as <script>
Why are you checking your POST['submit'] variable 5 times?
You only need to check it once.
if (isset($_POST['submit'])) {
$_SESSION['vege'] = isset($_POST['vege']) ? $_POST['vege'];
$_SESSION['vegan'] = isset($_POST['vegan']) ? $_POST['vegan'];
$_SESSION['peanut'] = isset($_POST['peanut']) ? $_POST['peanut'];
$_SESSION['gluten'] = isset($_POST['gluten']) ? $_POST['gluten'];
$_SESSION['vip'] = isset($_POST['vip']) ? $_POST['vip'];
}

Related

Retain Checked the checkbox inside While

this code is inside while after I submit the form instead of retaining what I checked it checked all after submitting.
I just want to happen after submitting the only check box i check is checked.
What should i do ?
<input type="checkbox" title ="<?php echo $sym ?>"<?php if(isset($_POST['poscon'])) echo "checked='checked'"; ?> name="poscon[]" value ="<?php echo $pc?>"><?php echo $pc?>
refer to in_array
<?php
if(isset($_GET["poscon"])) {
$_SESSION["poscon"] = $_GET["poscon"];
$dr=$_SESSION['poscon'];
if(isset($_POST['submit'])) {
if(!empty($_GET['poscon']))
$_SESSION['poscon'] = $_POST['poscon'];
$part=$_GET["poscon"];
}
$poscon=mysqli_real_escape_string($link,$_GET['poscon']);
$p = mysqli_query($link,"select distinct PossibleCondition,Symptoms from healthguide where Subpart like '%$poscon%' and PossibleCondition REGEXP '^[N-Z].*$' Order by PossibleCondition ");
while($r=mysqli_fetch_array($p)) {
$pc=$r["PossibleCondition"];
$sym=$r["Symptoms"];
if(isset($_POST) && isset($_POST['poscon']) && in_array($pc,$_POST['poscon']))
$strIsChecked='checked="checked"';
else
$strIsChecked=null;
echo '<tr>';
echo '<td><input type="checkbox" '.$strIsChecked.' title ="'.$sym.'" name="poscon[]" value ="'.$pc.'"></td>';
echo '<td>'.$pc.'</td>';
echo '</tr>';
}
}
?>
$_POST['poscon'] is a array. Run my script and see how it works.
<?php
/**
* File test.php
*/
// Store checked Values in Array $arrChecked
$arrChecked=array();
if(isset($_POST) && $_POST['poscon']) {
// Debug: Show all POST Vars
echo "<pre>"; print_r($_POST); echo "</pre>";
foreach($_POST['poscon'] AS $checkboxValue) {
// fill array with checked values
// e.g. arrChecked['foo'] = true;
$arrChecked[$checkboxValue] = true;
}
}
/**
* Note for HTML-Block:
* shorthand php if/else used
* http://stackoverflow.com/questions/4567292/overview-of-php-shorthand
*/
?>
<form action="test.php" method="post">
<input type="checkbox" name="poscon[]" value="foo" <?php echo (isset($arrChecked) && $arrChecked['foo'] ? 'checked="checked"' : '');?>> foo
<input type="checkbox" name="poscon[]" value="bar" <?php echo (isset($arrChecked) && $arrChecked['bar'] ? 'checked="checked"' : '');?>> bar
<input type="submit" value="go">
</form>

Checkboxes are checking out

I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php
if($room->trained == 1)
{ ?>
<input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]">
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked>
<?php echo "Y"; }
else{ ?>
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]">
<?php echo "N";
}?>
</td>
<Td><?php
if($room->active == 1) {
?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked>
<?php echo "Active"; }
else { ?>
<input type='checkbox' name="<?php echo $room->room_id; ?>"
<?php echo "Inactive"; } ?>
I used the trick with the "hidden" input before the checkbox, but the only problem is that it is not working. When I click on it, it resets all checkboxes to 0.
I think you are missing how the combo checkbox + hidden input does work.
So here you go freely inspired by this answer:
<input id="foo" name="foo" type="checkbox" value="1" />
<input name="foo" type="hidden" value="0" />
Looks like you do know, if you use the trick, that, if the checkbox is unchecked, it will not be present in the post. So to trick the form, we will always add an hidden field. And if the checkbox is checked, then the fact that it will be included in the post is going to override the value of the hidden input.
So for your specific problem :
<td>
<input type="checkbox" value="1" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]" <?php echo ($room->trained == 1) ? ' checked' : '' ?> /> Trained
<input type="hidden" value="0" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]"/>
</td>
Please note the use of the ternary operator on this part of the code <?php echo ($room->trained == 1) ? ' checked' : '' ?> which I may use a lot when writing html template.
Please also note the trick on the name trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>] which is needed because we cannot set the user_id as value of the input.
Then for the processing part :
if ( isset ( $_POST['submit'] ) ) {
foreach ( $_POST['trained'] as $ids => $value ) {
// This query needs protection from SQL Injection!
// ^ good point, on which I would suggest you using PDO and prepared statement :)
list($room_id,$user_id) = explode('_',$ids);
// ^ now need to explode the name on the underscore to get both user_id and room_id cf the trick above
$untrainQuery = "UPDATE room_users SET trained = '$value' WHERE user_id = $user_id AND room_id = $room_id";
$db->update ( $untrainQuery );
}
}
Wash, rinse, repeat for every checkbox you need and you should be good to go.

how to get checkbox value from database in php for update data?

in database values are stored as "A,B,C,D,E,F" etc.
now i have to fetch those data in the form for update.
i have to check the checkbox if it matches the value with database value.
i am doing this kind of code(which i know is wrong)
<input type="checkbox" name="time[]" value="free" <?php if(!strpos($row['best'], 'free')=="false") { echo "checked='checked'";} ?> />Free
<input type="checkbox" name="time[]" value="Open" <?php if(!strpos($row['best'], 'Open')=="false") { echo "checked='checked'"; }?>/>Open Source
<input type="checkbox" name="time[]" value="portable" <?php if(!strpos($row['best'], 'portable')=="false") { echo "checked='checked'"; } ?> />Portable
<input type="checkbox" name="time[]" value="support" <?php if(!strpos($row['best'], 'support')=="false") {
echo "checked='checked'"; }?> />Support
When strpos is 0 (first character), then it is equal to false if you use double = (==). You need to use ===false. Besides it should be false, not "false".
You can do in this way:
suppose you have four static values :
<
?php
$time = ['free', 'open' , 'portable', 'support']; // your checkboxes
$fromDb = explode(',', $row['best']);
foreach($time as $t):
?>
<input type="checkbox" name="time[]" value="<?php echo $t;?>" <?php if(in_array($t, $fromDb) { echo "checked='checked'";} ?> /><?php echo ucfirst($t);?>
<?php endforeach;?>

Dynamic radio button with self-post using PHP & MySQL

I'm drawing data from a MySQL database that dynamically places a question with 4-5 radio button choices for the answer. These radio buttons all belong to the same group, $quest_name. The first pass of the while statement will create 4 radio buttons belonging to radio group "question_1".
It creates 30-40 of these questions on a page, each with 4 radio buttons. I want the user to fill in all there answers and the page to post back to itself with the users answers still selected and then display if they were correct or not (functionality I still have to add).
I'm trying to follow http://www.w3schools.com/php/php_form_complete.asp as an example, but use a dynamically created radio button name instead.
This is what I have thus far:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$quest_num = $row["id"];
$question = $row["question"];
$option_1 = $row["option_1"];
$option_2 = $row["option_2"];
$option_3 = $row["option_3"];
$option_4 = $row["option_4"];
$option_5 = $row["option_5"];
$answer = $row["answer"];
$quest_name = "question_" . $row["id"];
echo "(" . $quest_num . ") " . $question . "<br>";
?>
<label>
<input type="radio" name=<?php echo $quest_name ?>
<?php if (isset(echo $quest_name) && echo $quest_name == echo $option_1) echo "checked"; ?>
value=<?php echo $option_1 ?>><?php echo $option_1 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_2 ?>><?php echo $option_2 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_3 ?>><?php echo $option_3 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_4 ?>><?php echo $option_4 ?>
</label>
<br>
<br>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit">
</form>
The part causing me grief so far is:
<?php if (isset(echo $quest_name) && echo $quest_name == echo $option_1) echo "checked"; ?>
I have also tried:
<?php if (isset($quest_name) && $quest_name == $option_1) echo "checked"; ?>
and:
<?php echo (isset($quest_name) && $quest_name == $option_1) ? "checked" : ""; ?>
How do you post back to the same page what they've selected? Like in this case I'm trying to say if "question_1" is set and "question_1" is equal to "converter" (the first radio button option) then have it checked when submit button is clicked.
I'm not that good at web development, but I'm trying to create a website to help my fellow electrical technician classmates.
Thanks for any help.
EDIT :
Using this line of code fixed the issue:
<?php if(isset($_POST[$quest_name]) && $_POST[$quest_name]==$option_1) { echo 'checked="checked"'; } ?>
What you need is called Radio Group. In HTML layer it is created with same name for all and different values for each like this:
<p>
<label>
<input type="radio" name="RadioGroup1" value="Value1" id="RadioGroup1_0">
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Value2" id="RadioGroup1_1">
Radio</label>
<br>
</p>
And when you want to get the user input in php layer you go like this:
<?php
//check if Radio Group 1 is set
if(isset($_POST['RadioGroup1'])) {
// print the value of Radio Group 1 choice
echo $_POST['RadioGroup1'];
}
?>
When you want to create a Selected Radio in HTML layer you go like this:
<input name="RadioGroup1" type="radio" id="RadioGroup1_1" value="radio" checked="checked">
So you have to check if user inputs the value of which radio like this:
<label>
<input type="radio" name="RadioGroup1" value="value1" id="RadioGroup1_0" <?php if(isset($_POST['RadioGroup1']) && $_POST['RadioGroup1']=='value1') { echo ' checked="checked"'; } ?>>
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="value2" id="RadioGroup1_1" <?php if(isset($_POST['RadioGroup1']) && $_POST['RadioGroup1']=='value2') { echo ' checked="checked"'; } ?> >
Radio</label>
You could use the following:
<input type="radio" name="<?php echo $quest_name ?>" value="<?php echo $option_1 ?>"
<?php if (isset($quest_name) && ($quest_name == $option_1)) echo "checked"; ?> />

Checking checkboxes from database values

I post values from check boxes into a database for a user profile. When the user goes to edit his/her profile I want the checkboxes that they selected previously to be checked so they don't lose that info after updating their profile. I have tried many different solutions but with no luck.
The check box values get entered into table name members_teachers into a column called focus and are seperated by a comma for example art,mathematics,dance etc I am not sure how close or far I am away at accomplishing my goal but I greatly appreicate any help or suggestions you can provide. Thank you very much in advance
My code to try and check the values is
<?php
$focusQuery = mysql_query("SELECT focus FROM members_teachers WHERE id = $member_id") or die;
while ($new_row = mysql_fetch_assoc($focusQuery)){
$focusRow = $row['focus'];
$focusValue = explode(',', $focusRow);
foreach($focusValue as $newFocus){
//echo $newFocus;
//echo "<br/>";
$result = mysql_query("SELECT focus FROM members_teachers WHERE focus LIKE '%$focusRow%'") or die;
if(mysql_num_rows($result) > $newFocus){
$checked = 'checked="checked"';
}
else{
$checked = '';
}
}
}
?>
This is my html
<label for="art-focus">Art</label>
<input name="focus[]" type="checkbox" value="Art" <?php echo $checked ?>>
<label for="math-focus">Mathematics</label>
<input name="focus[]" type="checkbox" value="Mathematics" <?php echo $checked ?>>
<label for="dance-focus">Dance</label>
<input name="focus[]" type="checkbox" value="Dance" <?php echo $checked ?>>
<?php
// Create connection
$con=mysqli_connect("hostname","username","pass","dbname");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT focus FROM members_teachers WHERE id = $member_id");
while($row = mysqli_fetch_array($result))
{
$focus=explode(",",$row['focus']);
?>
<input type="checkbox" name="focus[]" value="Art" <?php if(in_array("Art",$focus)) { ?> checked="checked" <?php } ?> >
<input type="checkbox" name="focus[]" value="Mathematics" <?php if(in_array("Mathematics",$focus)) { ?> checked="checked" <?php } ?> >
<input type="checkbox" name="focus[]" value="Dance" <?php if(in_array("Dance",$focus)) { ?> checked="checked" <?php } ?> >
<?php
}
?>
<?php
$focusedValues = array();
$focusQuery = mysql_query("SELECT focus FROM members_teachers WHERE id = $member_id") or die;
while ($row = mysql_fetch_assoc($focusQuery)){
$focusedValues = explode(',', $row['focus']);
}
?>
<label for="art-focus">Art</label>
<input name="focus[]" type="checkbox" value="Art" <?php echo in_array('Art', $checked) ?>>
<label for="math-focus">Mathematics</label>
<input name="focus[]" type="checkbox" value="Mathematics" <?php echo in_array('Mathematics', $checked) ?>
<label for="dance-focus">Dance</label>
<input name="focus[]" type="checkbox" value="Dance" <?php echo in_array('Dance', $checked) ?>
I don't know why you were SELECTing for the second time, that's pointless, you already know what's checked because it's in $focusedValues. Also, in your code, $checked would be empty if nothing was checked and checked="checked" otherwise. You obviously need a variable for each input, no?
<?php $hobby = $row['hobbies'];
$hobbies = explode (' ', $hobby);
?>
<input type="checkbox" name="hobbies[]" value="cricket" <?php echo in_array('cricket', $hobbies?'checked':'') ?> >cricket
<input type="checkbox" name="hobbies[]" value="singing" <?php echo in_array('singing' , $hobbies ?'checked': '') ; ?> >singing
<input type="checkbox" name="hobbies[]" value="football" <?php echo in_array('football', $hobbies ?'checked': '') ; ?> >footballl

Categories