This question already has answers here:
Getting checkbox values on submit
(10 answers)
Closed 6 years ago.
i am knew to php, and i want to know if there is a way to show the input based on the names that were checked, for example i have cat, dog and fish, if i choose dog and fish, i have to type the names of those animals.
here is the code to ask what animal do you have, and by checking and submit, it appears on the other page
<body>
<?php
$check_list[]=isset($_GET["check_list"])?$_GET["check_list"]:"";
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check;
}
}
?>
<form action="names.php" method="POST">
<h1>choose the animals you have, and type their names</h1>
<input type="checkbox" name="check_list[]" value="cat">
cat
<br>
<input type="checkbox" name="check_list[]" value="dog" >
dog
<br>
<input type="checkbox" name="check_list[]" value="fish" >
fish
<br>
<input type="submit" value="next">
</form>
and here is the other page, that show what animals you have selected, and on this page i want to show the inputs based on the checked
<body>
<?php
echo '<h3>You have select following animals</h3>';
foreach ( $_POST ["check_list"] as $animals )
echo '<p>' . $animals . '</p>';
?>
So in your code,
just replace $check_list[]=isset($_GET["check_list"])?$_GET["check_list"]:""; with $check_list = isset($_POST["check_list"]) ? $_POST["check_list"] : ""; and you should be good.
Also your variable $animals always carry one animal so it should be named animal.
and this:
$check_list[]=isset($_GET["check_list"])?$_GET["check_list"]:"";
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check;
}
}
can be improved to:
$check_list = isset($_GET["check_list"]) ? $_GET["check_list"] : null;
if ($check_list) {
foreach($check_list as $animal) {
echo "<p>My animal is: $animal</p>";
}
}
Next step is to learn more about security checks on user data!
Respectfully, good luck for you learning. PHP is beautiful ;)
Related
I have 5 check boxes from which a user can select one or more choices. The selected choices are then updated in database. The user's choices are then displayed/reviewed on another page. However my issue is that I want to show the updated choices together with the non-selected choices when doing a foreach loop in PHP.
These are the 5 check boxes
<input type="checkbox" name="interest[]" value="fishing">Fishing
<input type="checkbox" name="interest[]" value="camping">Camping
<input type="checkbox" name="interest[]" value="hiking">Hiking
<input type="checkbox" name="interest[]" value="swimming">Swimming
<input type="checkbox" name="interest[]" value="running">Running
<br><br>
<input type="submit" name="submit" value="Submit">
Heres the code that updates
if (isset($_POST["submit"])) {
$interestArr = $_POST['interest'];
$interest = new Interest();
$newArr = implode(',', $interestArr);
$interest->updateInterests($id=19, $newArr);
}
Heres the code that displays
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
foreach ($newArr as $data) {
echo '<input type="checkbox" name="interest[]" value="'.$data .'" checked>'.$data;
}
The update choices are stored under the interests column in DB like so
fishing,camping,running
And the foreach loop displays them checked check box with the correct corresponding labels.
How can I display the other check boxes that were not selected just so that the user might want to make changes?
Thanks.
Here's a simple example to illustrate the main idea. This code is intended to run in the single script.
The main ideas are:
Use a global list of interests to drive the form.
Keep a separate global list of checked check boxes which you can compare to determine if the checkbox should be checked.
when the form is submitted, populate the list which keeps track of checked items
render the form and compare the list of available checkboxes with checked checkboxes. If item found in both lists, it means that we want to display the checkbox as checked.
index.php
<?php
// Keep this outside of the if statement so the form has access to it.
$availableInterests = [
'fishing',
'camping',
'hiking',
'swimming',
'running',
];
// Keep this outside of the if statement so the form has access to it.
$selectedInterests = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Cast the posted interests to an array in case the user submitted an empty list.
// An empty list would be NULL if we didn't cast it.
$selectedInterests = (array)$_POST['interest'];
// foreach $selectedInterests insert into DB...
// Let this code `fall through` to render the form again.
// $selectedInterests is now populated and can be used in to the form below to keep the selected checkboxes checked.
}
?>
<form method="post">
<!-- Using the `global` $availableInterests array to drive our form. -->
<? foreach ($availableInterests as $interest): ?>
<!-- Do we want to render the checkbox as checked? -->
<?php $checked = (in_array($interest, $selectedInterests)) ? ' checked' : ''; ?>
<input type="checkbox"
name="interest[]"
value="<?php echo $interest; ?>"
<?php echo $checked; ?>>
<?php echo ucfirst($interest); ?>
<?php endforeach; ?>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Let's suppose you have an array of choice list like :
$choices = ["Fishing", "Camping" , "Hiking","Swimming" , "Running" ]
after the user select their choices
$interests = ["Fishing" , "Running" ];
In your case , the coresponding line is :
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
Let's suppose that $newArr is equal to $interests in may example.
foreach ($interests as $interest) {
echo 'you have choose '.$interest.PHP_EOL;
}
As result :
you have choose Fishing
you have choose Running
For not selected :
$notInterests = array_diff($choices,$interests);
foreach ($notInterests as $notInterest) {
echo 'you have not choose '.$notInterest.PHP_EOL;
}
As Result :
you have not choose Camping
you have not choose Hiking
you have not choose Swimming
To handle it in one loop :
foreach ($choices as $choice) {
if(in_array($choice,$interests )){
echo'you have choose '.$choice.PHP_EOL ;
}else{
echo 'you have not choose '.$choice.PHP_EOL;
}
}
Hope this help you.
To help others that might be in a similar situation I would like to post what is now a working solution at least for me based on Mohammed Yassine CHABLI's inspiration. Vantiya who was the first to comment really help me appreciate what was to follow. Thanks guys.
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$choices = $interest->showInterests($userid=19)->choices;
$selected = explode(',', $interests);
$choices = explode(',', $choices);
foreach ($choices as $choice) {
if(in_array($choice,$selected )){
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
checked>'.$choice;
}else{
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
unchecked>'.$choice;
}
}
I have a form of checkboxes as shown below:
<form method="POST" action="display.php">
<input type="checkbox" value="1" name="options[]">
<span class="checkboxText"> Fruits</span>
<input type="checkbox" value="2" name="options[]">
<span class="checkboxText">Vegetables </span><br><br>
<button class="button" type="submit" value="display">DISPLAY</button>
</form>
I get the options[] using $_POST['options'] and save the array of data in a variable. I want to display the array of fruits if the fruits checkbox is checked, the vegetables array if vegetables checkbox is checked and display both of them if both are checked and display a message saying "Fruits and Vegetables are healthy". This is the php code I have so far but it does not seem to work as I would like it to.
<?php
$values = $_POST['options'];
$n = count($values);
for($i=0; $i < $n; $i++ )
{
if($values[$i] === "1" && $values[$i] == "2")
{
//iteration to display both tables
echo 'Fruits and Vegetables are healthy';
}
else if($values[$i] === "1")
{
//display fruits
}
else if( $values[$i] == "2")
{
//display vegetables
}
}
?>
The problem with my php code is that is does not go into the first if at all. It just displays both tables from the other two ifs (since the echo is not displayed either). Is there any way I could solve this?
You shouldn't need a loop for this. You just need to check in $_POST['options'] for each of the values in question. I would suggest using the text you want to display as the values for your checkboxes so you don't have to convert from numbers to words.
<input type="checkbox" value="Fruits" name="options[]">
<span class="checkboxText"> Fruits</span>
<input type="checkbox" value="Vegetables" name="options[]">
<span class="checkboxText">Vegetables </span><br><br>
Then for the display, just output the fruits/vegetables arrays depending on whether or not those values are present in $_POST['options'].
if (!empty($_POST['options'])) {
echo implode(' and ', $_POST['options']) . " are healthy";
if (in_array('Fruits', $_POST['options'])) {
// show the fruits
}
if (in_array('Vegetables', $_POST['options'])) {
// show the veg
}
}
This question already has answers here:
PHP Text Field value shows incomplete data, only 1 word
(5 answers)
Closed 11 months ago.
I want to create a page which allows a user to select colours (among the listed ones, via checkboxes). When the user clicks on the submit button, all the selected colours should get displayed with their corresponding colours as their font colour.
Here is my code:
<?php
if(!isset($_POST['button'])) {
?>
Colours<br>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=post>
<input type="checkbox" name="colours[]" value="Red">Red<br>
<input type="checkbox" name="colours[]" value="Blue">Blue<br>
<input type="checkbox" name="colours[]" value="Green">Green<br>
<input type="checkbox" name="colours[]" value="Yellow">Yellow<br>
<input type="checkbox" name="colours[]" value="Pink">Pink<br>
<input type="submit" name="button" value="Show"> </form>
<?php
} else {
if (isset($_POST['colours'])) {
echo "Colours selected are:<br><UL type=circle>";
foreach($_POST['colours'] as $color)
echo "<LI><font color='echo $color'; >$color</font>";
echo"</UL>";
} else {
echo "No colour selected";
}
}
?>
There is a bug somewhere, the font colors are not as expected.
I want it like this image below:
Simply write
echo "<li><font color='$color'> $color </font></li>"; // complete li tag
other mistakes:-
a) form method attrubute should be method='post'
b) UL type=circle should be ul type='circle'
When appending a string to variable or another string, you must concatenate the values with a . (dot). for example:
echo("<li><font color=".$color.">".$color."</font>");
Try this;
echo "Colours selected are:<br><UL type=circle>";
foreach($_POST['colours'] as $color) {
echo " <LI><font color='".$color."'>'".$color."'</font></LI>";
}
echo"</UL>";
I've looked through a lot of questions, so forgive me if there is one that may help, but I've not been able to figure this out.
So I have a simple HTML form, that takes the users input for three categories: multiplayer, platform, and genre. This is the html code
<form method="post" action="gamebuddy.php">
<div class="players">
Please select one (or both) of the following: <br>
<input type="checkbox" name="players[]" value="No">Single Player<br>
<input type="checkbox" name="players[]" value="Yes">Multiplayers<br>
</div>
<div class="platform">
Please select your game system(s): <br>
<input type="checkbox" name="platform[]" value="XBOX">Xbox<br>
<input type="checkbox" name="platform[]" value="PS3">PS3<br>
<input type="checkbox" name="platform[]" value="PC">PC<br>
<input type="checkbox" name="platform[]" value="Wii">Wii<br>
</div>
<div class="genre">
Please select the genre(s) of game you would like: <br>
<input type="checkbox" name="genre[]" value="Action" >Action<br>
<input type="checkbox" name="genre[]" value="Casual">Casual<br>
<input type="checkbox" name="genre[]" value="Roleplaying">Role-Playing<br>
<input type="checkbox" name="genre[]" value="Shooter">Shooter<br>
<input type="checkbox" name="genre[]" value="Sports">Sports<br>
</div>
<div class="submit">
<input type="submit">
</div>
And then I have a PHP file that is used when the user clicks submit. Ideally, it takes the form inputs as a variable, and uses the SQLite statement to find the games the user can play based on his choices.
Here's the PHP code:
<div class="displaygames">
Based on your choices, these games seem suitable for you: <br>
<?php
if(!empty($_POST['players'])) {
foreach($_POST['players'] as $players) {
echo $players; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
if(!empty($_POST['platform'])) {
foreach($_POST['platform'] as $platform) {
echo $platform; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
if(!empty($_POST['genre'])) {
foreach($_POST['genre'] as $genre) {
echo $genre; //echoes the value set in the HTML form for each checked checkbox.
}
}
//This is to connect to the database
$db = new SQLite3('gamebuddy.db');
//Statement that uses variables to create list
$results = $db->query("SELECT * FROM games where multiplayer = '$players' and platform = '$platform' and genre is '$genre'");
//Displays List
while ($row = $results->fetchArray()) {
echo '<ul>';
echo $row['game'];
echo '</ul>';
}
?>
So everything works fine if you put in one answer for each category (for example, the user clicks "No" to multiplayer, "PS3" to platform, and "action" to genre). BUT if the user selects "Action" AND "Role-Playing", for some reason it only takes the last one the user selects, in this instance "role-playing".
So my question is how do I get the statement to show ALL of the games when there are multiple inputs.
Thank you for your help, I will answer any questions there may be, and of course mark the answer as solved if it helps. Thanks!
If u have array in for example $players, u can use implode function and "IN" statement in SQL:
"SELECT * FROM games WHERE multiplayer IN (".implode(",", $players).")"
let's say I have a list of checkboxes that the user selects.
<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
The user selected Water and it is added to the database. Now the user wants to update the list:
<input type="checkbox" name="utility[]" id="utility[]" value="Water" checked="checked"/>Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
How can I check that the utility has already been checked in PHP?
What I've done in the past, to save having hundreds of lines of bloat is this...
First compile all the html in a variable, without any "checked" instances.
$boxes = '';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />';
Now I loop over your array of fields to check. I've provided a sample array here too.
$already_checked = array('Water', 'Electricity');
foreach( $already_checked as $ac ) {
$find = 'value="' . $ac . '"';
$replace = $find . ' checked="checked"';
$boxes = str_replace($find, $replace, $boxes);
}
echo $boxes;
You could do something like this:
<input type="checkbox" name="utility[]" value="Water"
<?= in_array('Water', $utilities) ? 'checked="checked"' : '' ?>"
/>
(The $utilities variable above is a stand-in for something like $_REQUEST['utilities'], depending on how your code is structured.)
Like that?
<input type="checkbox" name="utility[]" id="utility[]" value="Water"
<?php
if(isAlreadyChecked("Water"))
echo "checked=\"checked\""
?>
/>Water<br />
<?php
function isAlreadyChecked(value)
{
//Check if it is already checked and return a boolean
}
?>
I tried every variant of the in_array conditional out there and could NEVER get this to work (checking off the checkboxes whose values had been previously selected and thus inserted into the database). I tried complex queries with table joins and no luck with that either. I finally gave up and generated a display:hidden div that opened the array (which for some odd reason I had to IMPLODE rather than explode) and listed its items as comma-separated text. Then I tossed in a little jQuery indexOf() magic to determine if the value of each checkbox was part of said array or not. Took me 10 minutes flat to do this with jQuery, very simple.
Here's some sample code that is live and working fine:
<div class="categories">
<span class="keywords"><?php $categories = array(); $categories = implode(', ', $keywords); echo $categories ?></span>
<em>Please verify category selections with each update.</em><br/>
<?php
include 'db.php';
$sql = mysqli_query($con,"SELECT * FROM categoriesTable ORDER BY Category_Name ASC");
while ($row = mysqli_fetch_assoc($sql))
{
$key = urldecode($row['Category_Name']);
$id = urlencode($row['catID']);
echo "<input type='checkbox' name='Category_Key[]' value='$id' id='cat_$id' $chk> $key<br/>";
}
?>
</div>
CSS sets that div to invisible:
.keywords { display:none; visibility:hidden; }
and the jQuery portion:
$(document).ready(function() {
$('.categories input').each(function(index,data) {
var str=$('.keywords').text();
var catid = $(this).val();
var chk = str.indexOf(catid);
if (chk >= 0) {
$(this).prop('checked', true);
}
});
});
I hope this helps someone else who is stuck wondering why the in_array conditional is failing them. Since this falls in a twilight zone between data and UI regarding data persistence, I think it's a legit route to take. You have one "echo" statement to generate multiple checkboxes (there are around 40 categories in my situation here) and then a simple jQuery .each() to locate what was selected before and render its corresponding boxes as checked.