i am trying to import from mysql column as an exploded values (category id) from table called "products", and print it in a checkbox input, and check if the value (category id) equal to the (category id) in the table called "cats", to set checkbox to "checked", this is my code:
<?php
for($i2=0;$i2<$rowsZ22;$i2++){
//exploding
$catszz2 = explode(",", $bussSubcat);
//foreach start
foreach($catszz2 as $catzz2) {
if($catzz2==$row22[$i2]["id"]){
$ischecked2="checked";
}else{
$ischecked2="";
}
}
//foreach end
?>
<li><input type="checkbox" onclick="getElementById('cats<?=$row22[$i2]["parent"]?>').checked= true;" <?=$ischecked2?> value="<?=$row22[$i2]["id"]?>" name="subcats[]" id="" /> <?=$row22[$i2]["title"]?></li>
<?php
}
?>
the code is checking the last input only (last category)
any help ?
You're running a foreach before you actually output the checkbox...
So, the $isChecked variable is actually changing in your foreach, but only the last value of the loop will be printed.
You need to move your
<li></li>inside the loop of the $isChecked
I'm not sure if this is what you want, but here goes:
<?php
for ($i2 = 0; $i2 < $rowsZ22; $i2++) {
$catszz2 = explode(",", $bussSubcat);
foreach ($catszz2 as $catzz2) {
if ($catzz2 == $row22[$i2]["id"]) {
$ischecked2 = "checked";
} else {
$ischecked2 = "";
}
?>
<li>
<input type="checkbox"
onclick="getElementById('cats<?= $row22[$i2]["parent"] ?>').checked= true;" <?= $ischecked2 ?>
value="<?= $row22[$i2]["id"] ?>" name="subcats[]" id=""/> <?= $row22[$i2]["title"] ?>
</li>
<?php
}
}
?>
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
}
}
I'll introduce the problem with an image :
These are checkboxradio from jquery, and what I'm trying to do is
print these checkbox but not always the same way, because the content in the checkbox will differ every time (because depending on what a user previously entered in an array)
For exemple, the suggestion 1 is of length 3 on the image, but could have a different length another time, up to a length of 10.
As well as the total number of row, which could be 1 or 2 or ... Up to 10.
I tried to code something, but it doesn't work, mostly because it's kind of disgusting and probably is a wrong way of doing it.
<?php
/*
$words is a 2 dimensional array, which contains :
row -> specific type (ex : Metal's type / Water's name...)
column -> each words of a type (ex : Iron / Copper / Barium...)
*/
$i = 1; //Iterator through lignes
$j = 0; //Iterator through columns
$length = 0; //Length of the array
/*
Print a certain number of radio button type
*/
if(!empty($words['0']) && $i==1) {
$length = count($words['0']); //Needed to know how many radio button we have to show
debug($length);
echo('Mot : 1');
//Now things starts to be wrong
?>
<html>
<fieldset>
<legend>Choose one : </legend>
<!--
Print radio button depending on the number of words,
could be all of them, or only 1.
-->
</html>
<?php
if($j < $length) {
?>
<html>
<label for="radio-1">$words['0']['0']</label>
<input type="radio" name="radio-1" id="radio-1">
</html>
<?php
$j++;
}
if($j < $length) {
?>
<html>
<label for="radio-2">$words['0']['1']</label>
<input type="radio" name="radio-1" id="radio-2">
</html>
<?php
$j++;
}
if($j < $length) {
?>
<html>
<label for="radio-3">$words['0']['2']</label>
<input type="radio" name="radio-1" id="radio-3">
</html>
<?php
$j++;
}
if($j < $length) {
?>
<html>
<label for="radio-4">$words['0']['3']</label>
<input type="radio" name="radio-1" id="radio-4">
</html>
<?php
$j++;
}
?>
<!--... Up to 10 times-->
</fieldset>
</html>
<?php
}
$i++; //Moving to the next row
//Same as above, but on an other row
if(!empty($words['1']) && $i==2) {
$length = count($words['0']);
echo('Mot : 2');
//etc...
I know it's monstrous to veteran but I couldn't find something else.
So, is there a way of printing a various amount of checkboxes properly ?
ANSWER
Thanks to the answer of Pol, I managed to do something that's working, it's still a bit disgusting, but it's wayyy better than my original way :
<?php
$i=1;
foreach ($newkeywords as $words) {?>
<h2>Groupe <?php $i?></h2>
<fieldset>
<legend>word '<?php echo($words[0])?>' :</legend>
<?php foreach ($words as $word) {?>
<label for=<?php 'checkbox-'.$i ?>><?php echo($word)?></label>
<input type="checkbox" name=<?php 'checkbox'.$i ?> id=<?php
'checkbox'.$i ?></br>
<?php $i=$i+1;?>
<?php
}
$i=1;
?></br><?php
}
?>
Still eager for other answers, it probably could be done better
Im not sure I followed but if you have a variable named 'words' and depending on how many words the length would be different. You can solve this using a foreach.
foreach($words as $word) :
// here you just print the row
// because the foreach will go through all words one by one.
// if you dont know how to access $word you can use var_dump($word)
// and then figure it out
echo '<label for="radio-1">'.$word['0'].'</label>';
echo '<input type="radio" name="radio-1" id="radio-1">':
endforeach;
I have multiple checkboxes within a foreach loop and I need to keep the selected checkboxes checked after the form submission. The code is as below. Please help.
<? $i=0;
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
foreach($row=$val)
{
$id="chkbox".$i;
?>
<input type="checkbox" name="chkbx" onclick ="func()" id="<?echo $id;">? value="<?echo $val \n;?>" <? echo "$val";?>
Now where and how to include the checked property of the boxes..
You don't need foreach loop here
This can be done for checking multiple checkbox checked
<?php
$i=0;
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
$checked = "";
if($row['database_column_name']=$val){
$checked = "checked";
}
echo '
<input type="checkbox" name="chkbx" onclick ="func()" id="'.$id.'" value="'.$val.'" '.$checked.'>'.
$val
.'
';
}
?>
Works for me.
Suppose I have a form like this, where checkboxes are repeating fields:
<form action="" method="post">
<?php for($i=0; $i<3; $i++) { ?>
<input type="checkbox" name="ch[]" value="1">
<?php } ?>
<button type="submit" name="submit">submit</button>
</form>
I'm on WordPress and using custom meta boxes for dealing with it. So I declared the form within the callback function of the metabox, and receiving the values in another save function that's hooked with save_post and new_to_publish action hooks.
So what's happening: when I click on the button, the metabox callback submitted the form, and the hooked function receives it. (Can be visible at add_meta_box() WordPress Codex) Suppose my save function contains:
<?php
if( isset($_POST['submit']) ) {
$chb = $_POST['ch'];
$result = array();
foreach ($chb as $cb) {
$result[] = array( 'isactive' => $cb );
}
var_dump($result);
}
?>
It's showing that, checkboxes are not returning any value when unchecked. I considered all the server-side solutions mentioned here: Post the checkboxes that are unchecked
PROBLEM is, whenever the form is submitted, it's taking the checkboxes' values to an array(), so I can't check the array values like:
if( !isset( $_POST['ch'] ) || empty( $_POST['ch'] ) ) {
$chb = 0;
} else {
$chb = 1;
}
I also tried hidden field with 0 value, accompanied with array_unique(), but nothing seems work for me.
How can I deal with unchecked checkboxes in an array so that they can't be null, and my foreach can loop through all of 'em and store data accordingly, and correct?
I want to avoid JavaScripts solutions.
If you name the checkboxes with an index in them, like so:
<input type="checkbox" name="chk_<?php echo $i ?>" value="1">
Then you could loop through them like so:
<?php
$chkBoxes = array();
foreach ($_POST as $k => $v) {
if (strpos("chk_",$k) === 0) {
$cbIndex = str_replace('chk_', '', $k);
$chkBoxes[$cbIndex] = $v;
}
}
Then to test if a checkbox was checked and sent to the server, you could use:
<?php
if (isset($chkBoxes[$cbIndex]))
Remember - the value of the checkbox is only sent if it was checked: Does <input type="checkbox" /> only post data if it's checked?
Add a hidden field in the form with the number of checkboxes, and use the index $i for the array ch[]:
<form action="" method="post">
<input type="hidden" name="num" value="<?= $num = 3 ?>">
<?php for($i=0; $i<$num; $i++) { ?>
<input type="checkbox" name="ch[<?= $i ?>]" value="1">
<?php } ?>
<button type="submit" name="submit">submit</button>
</form>
Then:
<?php
if( isset($_POST['submit']) ) {
$chb = $_POST['ch'];
$num = $_POST['num'];
$result = array();
for($i=0; $i<$num; $i++) {
$result[$i]['isactive'] = isset($chb[$i]) ? 1 : 0;
}
var_dump($result);
}
?>
first of all i copied ideas from many people inside this forum! i only synthesized the way!
my function to get data from my base located inside the $anoigmata class:
function getall() {
$data = $this->_db->get('<table_name>', array('ID', '>=', 0));
$results = $data->results();
$rows = $data->count();
return array($results, $rows);
}
code inside the create function to save all the secondary options that are not presented on the site.
$fields_Κ = array('history' => serialize(array(
'checkboxes' => Input::get('checkboxes')
)),
);
$data = $this->_db->insert('ΚΕΛΥΦΟΣ', $fields_Κ);
return true;
the php-html code that shows the result
<form method="post">
<div class="form-group">
<label for="checkboxes[]">checkboxes title</label><br>
`<?php
for ($i=0; $i<$anoigmata->getall()[1]; $i++) {
echo "
<input type='hidden' name='checkboxes[$i]' value='0' />
<input type='checkbox' id='checkboxes[$i]' name='checkboxes[$i]' value='".$anoigmata->getall()[0][$i]->ΕΜΒΑΔΟΝ."' />".$anoigmata->getall()[0][$i]->ΠΕΡΙΓΡΑΦΗ."<br>";}?>`
`</div><button type="submit" class="btn btn-success">Submit</button></form>`
***ΕΜΒΑΔΟΝ and ΠΕΡΙΓΡΑΦΗ are the row names from my table that i'm saving!!!
i hope i helped a little..!