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']
Related
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 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.
Objective: Get the value of buttons from $_POST method, inside foreach loop
$projects= 'Project1, Project2, Project3'//from mysql database
$projectNames = explode(',', $projects); // to separate the project names to display one by one on button.
Displaying all the project names on buttons.
<?php foreach ($projectNames as $val):?>
<form action="projectSelected.php" method="post" id="project">
<button style="float:left" class="btn-default" value=""> <?php echo $val;?> </button>
Problem statement: When user clicks on button 'Project1', program should be able to get the value of button with $_POST['projectSelected'].
Help would be appreciated.
Set the value in hidden, and then post the value
<form action="projectSelected.php" method="post" id="project">
<input type="hidden" value="<?php echo $val ?>">
<input type="submit">
1) change the name of your variables :
$Projects => $projects (PHP convention)
2) add a trim after your explode function
$projectNames = array_map('trim', $projectNames);
3) use input submit instead of buttons (similar question)
<input type="submit" style="float:left" class="btn-default" name="project" value="<?php echo $val ?>"/>
Complete example:
$projects = 'Project1, Project2, Project3'; //from mysql database
$projectNames = explode(',', $projects); // to separate the project names to display one by one on button
$projectNames = array_map('trim', $projectNames);
Loop:
<form action="projectSelected.php" method="POST" id="project">
<?php foreach ($projectNames as $val) : ?>
<input type="submit" style="float:left" class="btn-default" name="project" value="<?php echo $val ?>"/>
<?php endforeach ?>
</form>
DO this:
<button style="float:left" name = 'projectSelected' class="btn-default"
value=""> <?php echo $val;?> </button>
what ever you set the name of button will becomes the key of $_POST array
I have a select option in foreach loop. In every loop I'm creating a div and inside div a select option. But problem is when I send select's value with post method I can't get option's correct posted value. For foreach first 2,3 item button is working and submitting form but when I try to submit other items' form button is not working I can't create unique name for select because I must assign post variable to a variable in action page.
I think problem is about unique select name="", I can't give an unique name to select because I need it's name in action page as you know. How can I solve this stupid thing.?
<?php
foreach($a as keywords_arr){
?>
<form name="<?= $keywords_arr["keyword_id"]?>" method="post" action="actions/myaction.php">
<div class="modal-body">
<label for="tagler">Bla bla</label>
<select name="tagler" style="width: 100%;" class="form-control">
<?php
$all_tags = $db->query("SELECT *****");
$all_tags->setFetchMode(PDO::FETCH_ASSOC);
$all_tags_arr = $all_tags->fetchAll();
foreach ($all_tags_arr as $tag) {?>
<option value="<?= $tag["tag_id"] ?>"><?= $tag["tag_name"] ?></option>
<?php } ?>
</select>
<input type="hidden" name="kw_id_label" value="<?= $keywords_arr["keyword_id"] ?>"/>
<br><br>
<span id="result_lbl_"></span>
</div>
<div class="modal-footer">
<button id ="btn_<?= $keywords_arr["keyword_id"] ?>" type="submit">Save</button>
</div>
</form>
<?php}?>
myaction.php page
<?php
$tag = $_POST["tagler"];
$keyword_id = $_POST["kw_id_label"];
?>
Fiddle example:See example
You should declare select as array like tagler[]
<select name="tagler[]" style="width: 100%;" class="form-control">
Now in your php file use print_r($_POST), you will get selected options in array.
You can create dynamic select names in loop but in addition to that create hidden field as array which will save names of all select value generated. so in POST you will read hidden value to identify select boxes.
<?php
foreach($a as keywords_arr){
?>
<form name="<?= $keywords_arr["keyword_id"]?>" method="post" action="actions/myaction.php">
<select name="tagler<?php echo $keywords_arr["keyword_id"]?>" style="width: 100%;" class="form-control">
---
---
<input type = "hidden" name="select_boxes_name[]" value="<?php echo tagler<?php echo $keywords_arr["keyword_id"]?>">
after form post read select_boxes_name[] array to identify select boxes posted.
The unique id for select name="" is not your problem. The only problem I found is that you have the last php tag too close to the closing bracket and the intepreter doesn't recognize it. Please, try to create space between the closing bracket.
Change this:
<?php}?>
to this:
<?php } ?>
(UPDATE)
Use the below code for myaction.php:
<?php
$post_name = "uniquename";
$post_len = strlen($post_name);
foreach ($_POST as $key => $value)
{
//if the name of the current post begins with "uniquename"
if (substr($key, 0, $post_len) == "uniquename")
{
$index = $post_len;
$post_id = (int)substr($key, $index);
echo "post_id = " . $post_id . "<br/>key = " . $key;
// do your stuff here...
break;
}
}
?>
Here, we filter the POST variables and when we find the right one, we extract the ID from it (the ID in our case is the numeric part after the "uniquename". e.g. From uniquename5) the ID (post_id) will be 5.
What I am trying to do is use php to pull a variable number of records from a database. I want to let the user to be able to click on the text and it will switch the text out for an input box and will update the database on submit.
I am aware of how to do this with the onclick attribute, and passing the javascript function the id number that corresponds to the row in the mySQL database. I am trying to determine how I could do this using Unobstrusive Javascript techniques.
Here is the portion of the code that creates the divs, when the user clicks on the zone, account_number, dv or address fields it will switch out the text for the input box as I said above.
while($row = mysql_fetch_array($query)) {
$business_name = $row['business_name'];
$resource_id = $row['resource_id'];
$totaldv += $row['dv'];
if(!in_array($row['zone'], $zoneArray)) {
$zones .= $row['zone'] . " ";
array_push($zoneArray, $row['zone']);
}
$account_numbers .= "
<div>". $row['zone'] . "</div>
<div>" . $row['account_number'] . "</div>
<div>" . number_format($row['dv']) . " kW</div>
<div>" . $row['street_address'] . " " . $row['city'] . ", " . $row['state'] . "</div>
";
}
The problem I am encountering lies in that a customer could have 1 account, or 83 accounts and I need to be able to switch out the correct text for an input box and pass the id of the row from the database to the form. I was thinking of maybe using applying a class to the certain fields?
I have done something like this before, but it was always a static # of inputs, so I was able to hide the text and show the input box which was generated when the page was loaded. Something along the lines of this (granted it was not Unobtrusive)
$content .= "
<tr>
<td width=35><IMG SRC=images/$i.png height=20></td>
<td width=35 id=rank".$i.">$rankImages</td>
<td width=380>
<span id=text".$i." style=\"cursor:pointer;\" onclick=\"editItem($i);\">".$itemArray[$i]."</span>
<span id=$i"."input>
<input id=$i type=text value=".$itemArray[$i].">
<IMG SRC=images/save.png style=\"cursor:pointer;\" onclick=\"saveItem($i);\">
<IMG SRC=images/cancel.png style=\"cursor:pointer;\" onclick=\"cancelEdit($i);\">
</span>
</td>
</tr>";
function editItem(line_num) {
$("#text" + line_num).hide();
$("#" + line_num + "input").show();
}
The way I would go about it would be to use data-* attributes and then access that data using jQuery's .data() function. A shorter, but similar-looking, example of how your HTML might look:
<div class="editable-row" data-row-id="1">
<span class="uneditable">row one</span>
<input type="text" value="row one" />
</div>
<div class="editable-row" data-row-id="2">
<span class="uneditable">row two</span>
<input type="text" value="row two" />
</div>
<div class="editable-row" data-row-id="3">
<span class="uneditable">row three</span>
<input type="text" value="row three" />
</div>
<div class="editable-row" data-row-id="4">
<span class="uneditable">row four</span>
<input type="text" value="row four" />
</div>
And your JavaScript would look like this:
$(document).ready(function () {
$(".editable-row").on("click", function () {
var $this = $(this),
rowId = parseInt($this.data("rowId"), 10);
$this.find("input").show();
$this.find(".uneditable").hide();
// do something with rowId
});
});