I have already posted this but finally I didn't figure this out.I have a php form with some checkboxes (some of them are enabled and some disabled). Each of these has an id (id1=1, id2=2, id3=3, ...) which comes from database.
So when I submit the form I want to store these id's in a database table like this: if I choose only the 1st checkbox which has id=1 I should store '1' on my table and if I choose 1st and 3rd I should store '1, 3'. The problem is that I choose only the 1st and the stored data is '1, 2, 3, 4' because I have 4 checkboxes ENABLED.
PHP form :
<form method='post' action='insert.php'>
.
.
.
while($row_select4 = $stmt_select4->fetch(PDO::FETCH_ASSOC)){
if($form_points>=$row_select4['points']) {
$points = $row_select4['points'];
echo '
<div>
<div class="feed-activity-list"><div style="border: 0.5px solid green; border-right-style:none;" class="input-group m-b"><span class="input-group-addon">
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt[]" value="'.$points.'"></span>
<input type="hidden" name="opt2[]" value="'.$row_select4['id'].'">
<div class="feed-element">
<a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="'. $row_select4['image_url']. '"
</a>';
?>
<button type="submit" id="submit" name="eksasrgirwsh" class="btn btn-w-m btn-primary">ΕΞΑΡΓΥΡΩΣΗ</button>
</form>
IMPLODE before insertion :
if(isset($_POST['opt2'])){
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$sliced = array_slice($gift, 0, -1);
$gift_id = implode(", ", $sliced);
}
And I store $gift_id in the table..
Check :
if(isset($_POST['opt'])){
$total_points = 0;
$points = array_values($_POST['opt']);
foreach ($points as $value) {
$total_points += $value;
}
echo $total_points;
$gift_ids = '';
$gift = array_keys($_POST['opt']);
foreach ($gift as $key => $value) {
$gift_ids = $value;
$gift_ids2 = implode(", ", $gift_ids);
}
echo $gift_ids2;
}
Instead of using separate hidden controls to store the ids, use the name property of the checkboxes to do this:
'...
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt['. $row_select4['id'].']" value="'.$points.'"></span>
...';
The name of a checkbox will be like name="opt[3]" for id 3 record.
In the php script processing the form submission array_keys($_POST['opt']) will give you the gift ids, while array_values($_POST['opt']) will return the points. You will know which point is associated with which gift id because the keys of the $_POST['opt'] are the gift ids.
Pls also note that storing multiple values in a comma separated string in a single field is not really considered a good practice. You should normalise your data structure and store the separate values in separate records.
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 am working on html form present in a php file as shown below in which I want to count the entered html input values.
Php/HTML Code:
<form method="post" style="display: inline-block; margin-left: auto; margin-right: auto; text-align: left;">
<div style ="display:flex; align-items: baseline;">
Articles (EN)
<input type="text" name="articles_id_en" style="width: 30%;height: 22px;" value="<?php if($data->{"articles_id_en"}<>''){echo $data->{"articles_id_en"};} ?>">
Articles (FR)
<input type="text" name="articles_id_fr" style="width: 30%;height: 22px;" value="<?php if($data->{"articles_id_fr"}<>''){echo $data->{"articles_id_fr"};} ?>"><br>
</div>
<div style ="display:flex; align-items: baseline;">
Articles Entered (EN)
<input type="text"style="width: 30%;height: 22px;" value="<?php $values = $_REQUEST['articles_id_en']; $delimiter = ','; $valuesCount = count(explode($delimiter, $values)); echo "Values Count: " . $valuesCount . "<br>" . PHP_EOL; ?>">
Articles (FR)
<input type="text" name="articles_id_fr" style="width: 30%;height: 22px;" value="<?php if($data->{"articles_id_fr"}<>''){echo $data->{"articles_id_fr"};} ?>"><br>
</div>
<div>
<button type="submit">Save</button>
</div>
</form>
On hitting save, its get saved in a JSON as shown below with their list of values entered. At this moment, I have entered 149968, 149939, 149883, 149877, 149876, 149847, 154303 values so in JSON its showing like this:
{"articles_id_en":"149968, 149939, 149883, 149877, 149876, 149847, 154303"}
Below is the section of the screenshot of the form belonging to the above html/php code:
After entering the values, it display like this:
Following is the html code on inspect:
<input type="text" name="articles_id_en" style="width: 30%;height: 22px;" value=" 14996, 14993, 14988, 14987, 14987, 14984, 15430">
Problem Statement:
I am wondering what php code I need to add so that I can get the count of input values entered.
<form method="post">
<input type="text" name="articles_id_en" style="width: 30%;height: 22px;" value=" 14996, 14993, 14988, 14987, 14987, 14984, 15430">
<input type="submit">
</form>
<?php
if(isset($_REQUEST['articles_id_en'])) {
$values = $_REQUEST['articles_id_en'];
$delimiter = ',';
$valuesAsArray = explode($delimiter, $values);
$valuesCount = count($valuesAsArray);
} else {
$valuesCount = 0;
}
echo "Values Count: " . $valuesCount . "<br>" . PHP_EOL;
Have a look at this post about getting values from form
PHP function explode creates an array from the value="value1, value2" string that you get with $_GET['articles_id_en'];. The explode function creates an array with one entry per value that is separated with $delimiter character. Note that if values entered into form's input are separated with different character than , the solution will not work because explode looks for a specific character to divide a single string into multiple ones that it places inside an array.
count() just gives an integer number of items that it has between its () so if the array that is returned by explode() has 5 elements it will give an integer = 5.
result:
and after hitting submit:
First, convert your value data in an array using explode() and then count it using count().
if(isset($_POST['articles_id_en'])){
$value = $_POST['articles_id_en'];
$myArray = explode(',', $value);
echo $count_numbers = count($myArray);
}else{
echo "Form not submitted yet";
}
Here, we can also try and use preg_match_all that might work:
Notes:
We need to make sure, that each entry consists of valid digits, using i.e. this regex /([0-9]+)/m
However, it might be also the case where an entry contains a non-digit value in between, such as 149a93, in this case, we have to adjust our regex to overcome this problem by using word boundry, like so /(\b[0-9]+\b)/m
Then, our code might look like:
if(isset($_REQUEST['articles_id_en'])) {
$values = $_REQUEST['articles_id_en'];
$re = '/(\b[0-9]+\b)/m';
preg_match_all($re, $values, $matches, PREG_SET_ORDER, 0);
$count = sizeof($matches);
echo $count;
}
Demos
Regex: https://regex101.com/r/afKiC9/2
PHP: http://sandbox.onlinephpfunctions.com/code/07a370a52eb6c8d10cdbde9e2427af839a4a988a
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 have a form with 4 or more checkboxes.The form is created by a while loop and has data from database table.Each checkbox represents a gift and each gift has a unique id (id1=1, id2=2, id3=3, ...) in database.So user can choose one or more gifts and click the submit button to store his choice.So I need php implode() function to get the string of what choices user made.For example if he chooses the 1st and the 2nd checkbox/gift the value that must be stored should be 1, 2.Instead of this I always have different stored data and don't match with user choices..Any ideas?
Form :
<form method='post' action='insert.php'>
.
.
.
while($row_select4 = $stmt_select4->fetch(PDO::FETCH_ASSOC)){
if($form_points>=$row_select4['points']) {
$points = $row_select4['points'];
echo '
<div>
<div class="feed-activity-list"><div style="border: 0.5px solid green; border-right-style:none;" class="input-group m-b"><span class="input-group-addon">
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt[]" value="'.$points.'"></span>
<input type="hidden" name="opt2[]" value="'.$row_select4['id'].'">
<div class="feed-element">
<a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="'. $row_select4['image_url']. '">
</a>';
?>
<button type="submit" id="submit" name="eksasrgirwsh" class="btn btn-w-m btn-primary">ΕΞΑΡΓΥΡΩΣΗ</button>
</form>
Also (before insertion into table) :
if(isset($_POST['opt2'])){
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$sliced = array_slice($gift, 0, -1);
$gift_id = implode(", ", $sliced);
}
This is what I use to get the chosen gift_ids and create the string of them
Form updated:
<input type="hidden" disabled="disabled" name="opt2[]" value="'.$row_select4['id'].'">
Code for getting gift_ids:
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$gift_id = implode(", ", $gift);
}
No need for array_slice
in your php code:
$gift = $_POST['opt2'];
$gift_id = implode(", ", $gift);
By using this, you can get the result you wish.
Edit:
The reason you get all 1,2,3,4 is that you use hidden for gift id.
Try to add disabled="disabled" to the hidden tag which you dont want send to server. After this, you can get correct ids using $_POST['opt2']
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.