I have a loop below that is showing a quantity box and includes a hidden field containing the product name.
I want these to be tied together so if out of 100 inputs the user changes the quantity of input 90, then and want the hidden field input 90 to be tied to it.
This then gives me the quantity and the product name for items that have more than zero.
<?php if(get_field('sizes')) {
while(the_repeater_field('sizes')) { ?>
<input type="text" name="quantity[]" value="0"> <?php the_title(); ?>
<input type="hidden" name="product[]" value="<?php the_title(); ?>">
<?php } } ?>
I want to tie these two together so it would echo out the following:
1 x Product One
10 x Product Three
20 x Product Eight
How can I output the quantity AND product name only if the quantity is more than zero?
This is the actual code used:
<?php if(get_field('sizes')) { ?>
<?php while(the_repeater_field('sizes')) { ?>
<tr>
<td width="150"><p><?php echo the_sub_field('size'); ?></p></td>
<td width="30" align="right">
<p>
<input type="text" class="quantity" name="quantity[]" style="width:15px;text-align:center!IMPORTANT;margin-left:10px;" value="0">
<input type="hidden" class="productinput" name="product[]" value="<?php echo the_title(); ?> - <?php echo the_sub_field('size'); ?>"></td>
</p>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td width="150"><p>Quantity</p></td>
<td width="30" align="right">
<p>
<input type="text" class="quantity" name="quantity[]" style="width:15px;text-align:center!IMPORTANT;margin-left:10px;" value="0"><?php echo the_sub_field('size'); ?>
<input type="hidden" class="productinput" name="product[]" value="<?php echo the_title(); ?>">
</p>
</td>
</tr>
<?php } ?>
This is then creating the code ready to be output in an email:
$quantities = array_combine($_POST['product'], $_POST['quantity']);
foreach ($quantities as $product => $quantity) {
if ($quantity > 0) {
$productresults = "$quantity x $product";
}
}
This is the page I'm working on. If you click on "Get Quotation", the second step is the code above.
#Sn0opy
foreach($_POST['quantity'] as $check) {
if($check > 0) {
$quantityresults .= $check."\n";
}
}
echo $quantityresults;
You obviously need to iterate over both arrays in tandem so that you can see if a product's quantity is nonzero in order to decide if it should be displayed.
In general foreach is an awkward tool for this job, and the way to go is with a for loop and indexing into both arrays using the same counter. However, in this specific case you can easily transform your two arrays into one where the keys are product names and the quantities are the values using array_combine:
$quantities = array_combine($_POST['product'], $_POST['quantity']);
You can then easily iterate with foreach:
foreach ($quantities as $product => $quantity) {
if ($quantity > 0) {
echo "$quantity x $product<br>";
}
}
I recommend using the product ID in the quantity array like this:
<input type="text" name="quantity[<?php the_title(); ?>][]" value="0">
Ofc, this is not the answer you were looking for, but an alternate version which should also work.
Rob, I see you have a good answer but you might like to be aware of a significant issue.
By posting independent quantities[] and products[], then you are relying on the two serializations being conformal with each other - ie. that both are serialized in DOM order - hence that the indexes of $_POST['quantity'] and $_POST['product'] correspond element-by-element. For me, this is not a completely safe assumption - see the selected answer here.
It would be far safer, and more conventional, to have one <input> field per product, named with a representation of product-id and a value representing quantity. Thus, product-ids and their values are guaranteed to correspond.
Client-side and server-side code would need to be reviewed accordingly.
Related
I am having a issue in getting the correct value from the table.
The issue I encountered:
When I choose the second checkbox the and input a quantity, it is Undefined offset: 0
But the value of the checkbox is working and correct.
What I am expecting is when I choose the second or other checkbox (exclude first checkbox), I should get the value of that input field.
HTML
<?php foreach($results as $row) { ?>
<tr>
<td><input type="checkbox" name="products[]" value="<?php echo $row->items_id; ?>"></td>
<td><?php echo $row->item_name; ?></td>
<td><input type="number" name="quantity[]" class="form-control"></td>
</tr>
<?php } ?>
<input type="submit" name="process" class="btn btn-primary" value="Process">
PHP
$quantity = $_POST['quantity'];
$products = $_POST['products'];
$count_selected = count($products);
for($i=0; $i< $count_selected; $i++){
var_dump($quantity[$i]); exit;
}
The problem with checkboxes is that an unchecked one submits no value so your $_POST['products'] and $_POST['quantity'] arrays may have different lengths.
I'd combine using a hidden input with specific array indexes.
For example
<?php foreach($results as $row) : ?>
<tr>
<td>
<input type="hidden" name="products[<?= $row->items_id ?>]" value="0">
<input type="checkbox" name="products[<?= $row->items_id ?>]" value="1">
</td>
<td><?= htmlspecialchars($row->item_name) ?></td>
<td><input type="number" name="quantity[<?= $row->items_id ?>]" class="form-control"></td>
</tr>
<?php endforeach ?>
Then the arrays will have the same indexes and you can iterate them with a foreach
foreach ($_POST['products'] as $itemId => $checked) {
// $checked represents the state of the checkbox
// you can access quantity via $_POST['quantity'][$itemId]
}
You could even create a nice filtered array of quantities via
$selections = $_POST['products'];
$quantities = array_filter($_POST['quantity', function($itemId) use ($selections) {
return $selections[$itemId];
}, ARRAY_FILTER_USE_KEY);
first, define array variable.
$products =array( );
$quantity=array( );
other wise every thing seems fine.
I'm working on a form that uploads an image to a server. The form contains checkboxes and select boxes formatted to a <table>. Each table row contains two columns. The First column iterates through a mysql query that displays a list of items (24 items to be exact) that is paired to a checkbox. The 2nd column iterates through a mysql query that displays list of clients.
What needs to be done are as follows:
When the form gets uploaded (via POST or GET) the checkboxes which only have check gets passed.
convert the subs_id (name parameter for the select box) to an array for easy processing for mysql insert.
Code Below. Thanks in advanced!
<form method="post" enctype="multipart/form-data" action="upload2.php">
Name: <input type="text" name="item_desc" value="">
Show Date: <input type="text" name="upload_date" class="date" size="10"> to <input type="text" name="expiry_date" class="date" size="10">
Item: <input type="file" name="item"> Display Length: <input type="number" value="8" name="show_time" size="3" style="width:50px"> secs
<table class="data-list" width="100%">
<tr>
<td>Widget</td>
<td>Client</td>
</tr>
<?php foreach($instance as $item):?>
<tr>
<td><input type="checkbox" id="checkAll"/> <?php echo $item['name']; ?></td>
<td><select id="selectBox" name="subs_id[]">
<option selected="selected" value="none">Select Client</option>
<?php foreach($subs as $client): ?>
<option value="<?php echo $item['id'] . '-' . $client['id']; ?>" client="<?php echo $client['client_name']; ?>" ><?php echo $client['client_name']; ?></option>
<?php endforeach ?>
</select>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<input type="submit" value="upload">
</form>
<input type="checkbox" id="checkAll" name='client[]' value ="1" /> <?php echo $item['name']; ?>
name and value is missing
1 .Change your checkbox code to
<input type="checkbox" id="checkAll" name="checkId[]" value="<?php echo $item['name']; ?>"/> <?php echo $item['name']; ?>
Here, I am taking name as array checkId[] and value of checkbox value="<?php echo $item['name']; ?>"
This should work for you.
Your select box is fine. There is no need to change it. you can find value of select box by checking index.
I figured it out. What I did was detect when there was a change on the select box and assign the value of the select box to the check box's value.
$(".selectBox").change(function() {
$(this).parent().siblings().children('input').attr('value',$(this).val());
});
then, on the upload2.php, I used the code below to get the value of only the boxes with check
if(!empty($_POST['checkId'])) {
$filename = $this->unique_filename($this->extract_ext( $_FILES["item"]["name"]));
$folder = dirname(__FILE__) . '/items';
move_uploaded_file($_FILES['item']['tmp_name'],"{$folder}/{$filename}");
foreach($_POST['checkId'] as $check) {
//save to db
$split = explode("-",$check);
$subs_id = $this->use_table('clients')->where('client_name like "' . $split[2] . '%"')->where('site_id=' . $split[1])->fetch();
//$subs_id = $this->query('select * from clients where client_name like "Trinoma%" and site_id=1');
//print_r($subs_id[0][id]);
$data = array(
'item_name'=> 'widgets/' . strtolower(get_class($this)) . '/items/' . $filename,
'show_time'=> $_POST['show_time'],
'instance_id'=> $split[0],
'item_desc'=>$_POST['item_desc'],
'subs_id'=> $subs_id[0][id]
);
$this->use_table(TBL_NAME)->insert($data)->execute();
$mid = $this->last_insert_id();
$this->use_table(TBL_SCHED)->insert(array(
'multirotator_id'=>$mid,
'show_from'=>'00:00',
'show_to'=>'23:59',
'upload_date'=>$_POST['upload_date'],
'expiry_date'=>$_POST['expiry_date']
))->execute();
} //end of foreach
} //end of if(!empty($_POST['checkId']))
and voila! working code for me.
I have a form with rows which are populated from a table. Each row has a "checkbox" which the user can check or not.
When the form is submitted I want to be able to read which checkbox have been selected and insert the result in to a data table.
My code so far
FORM:
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table
<?php do { ?>
<tr>
<td>input type="text" name="InspectRoomNo" value="<?php print $row_InspectItems['AuditItemNo']; ?>"></td>
<td>php echo $row_InspectItems['AuditItem']; ?>td>
<td>input name="check[]" type="checkbox" ></td>
</tr>
<?php } while ($row_InspectItems = mysql_fetch_assoc($InspectItems)); ?>
<input type="submit" value="Insert record">
</table>
The insert: fetchs $Items from table
while($row = mysql_fetch_assoc($Items))
{
$array[] = $row['AuditItem'];
}
foreach($array as $id) {
$AuditItemID = mysql_real_escape_string($id);
if(isset($_POST['check'])){
$Checked = mysql_real_escape_string($_POST['check'][$row]);
}
}
The problem I am having is the returned values for all the checkbox is true, even if a checkbox was not selected.
Can anyone help me sort this issue.
Many thanks.
Do it like this:
if(!empty($_POST['check'])) {
foreach($_POST['check'] as $check) {
echo $check;
}
}
You should put the item id inside the checkbox name:
<td><input name="check[<?= $row_InspectItems['AuditItem']; ?>]" type="checkbox" /></td>
Then, you can simply iterate over it:
foreach ($_POST['check'] as $id => $value) {
// do stuff with your database
}
I'm assuming than whomever runs this script is trusted, because it would be easy to forge the list of ids; make sure the current user has permissions to update those records.
What is happening, is that only selected checkboxes get sent to the server, so you will see that your $_POST['check'] array (this is an array!) is smaller than the number of items you have displayed on the screen.
You should add your ID's so that you know what checkboxes got checked and adapt your php processing code to handle an array instead of a single value.
You are also overwriting your InspectRoomNo every row, so you should use an array there as well.
The form side would look something like:
<td><input type="text" name="InspectRoomNo[<?php echo row_InspectItems['AuditItemNo']; ?>]" value="<?php print row_InspectItems['AuditItemNo']; ?>"></td>
<td><?php echo $row_InspectItems['AuditItem']; ?></td>
<td><input name="check[<?php echo row_InspectItems['AuditItemNo']; ?>]" type="checkbox" ></td>
I have a problem showing the quantity for each article I check through a form which is getting data from a MySQL database I made.
Here is my code:
<?php foreach ($results_articles as $input) : ?>
<input type="text" name="<?php echo $input->id_article; ?>_txtbox[]" style="text-align: center; width:30px;"></input>
<input
type="checkbox"
name="checked_articles[]"
value="<?php echo $input->id_article; ?>">
<?php echo "(".
($input->ref_article).")".
($input->nom_article)." (".
($input->prix_article)." €)"; ?><br>
<?php endforeach; ?>
So, the "checked_articles" are showing up properly on my next page; but I really don't know how to show the quantity for each article checked.
I would like help from you !
Thanks! If you have any other infos, I'll reply of course!
I presume "quantity" is put in the text input, if so it should be accessible using:
foreach ($_POST['checked_articles'] as $checked_id)
{
$quantity = $_POST[$checked_id . '_txtbox'];
}
However, since the txtbox input is named to become an array, $quantity would result in an array. Maybe that is not what you intend. Then you could do it this way instead:
<input type="text" name="txtbox[<?php echo $input->id_article; ?>]" style="text-align: center; width:30px;" />
Having that, the textbox would be accessible using:
$_POST['txtbox'][$checked_id];
I have an html table I've updated to use checkboxes to be able to delete multiple files:
<table>
<thead>
<tr>
<th>Camera Name</th>
<th>Date Created</th>
<th>Video Size</th>
<th>Video Length</th>
<th>
<button type="submit" class="deletebutton" name="delete_video" value="Delete" title="Delete the selected videos" onClick="return confirm('Are you sure you want to delete?')">Delete</button><br>
<input type="checkbox" name="radioselectall" title="Select All" />
</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_videos;$i++)
{
//do stuff
//Note: I'm looping here to build the table from the server
?>
<tr >
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo setlocalTime($result_videos[$i]["video_datetime"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo ByteSize($result_videos[$i]["video_size"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo strTime($result_videos[$i]["video_length"]); ?>
</td>
<td>
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="checkbox" name="radioselect" title="Mark this video for deletion"/>
<input type="hidden" name="video_name" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
</form>
</td>
</tr>
I started with first creating some jquery code to create a select all/deselect all button in the table heading and just a test to show I can find which boxes are checked. That all works:
//selectall checkboxes - select all or deselect all if top checkbox is marked in table header
$("input[name='radioselectall']").change(function()
{
if( $(this).is(':checked') )
{
$("input[type='checkbox']","td").attr('checked',true);
}
else
{
$("input[type='checkbox']","td").attr('checked',false);
}
});
//process checkboxes - which ones are on
$(".deletebutton").click(function() {
$("input[name='radioselect']:checked").each(function(i){
alert(this.value);
});
});
So the part where I'm stuck is I don't know where to go from here. I need to pass all the video_names of all the videos selected (with the checkboxes). video_name is part of a hidden field in my form. So I need to pass that to my php function when the delete button is selected. Not really sure how to tackle this. Hope this makes sense.
Simple solution maybe:
Change your checkboxes to have a value of 1 and a name of $result_videos[$i]["video_name"]; in the table rows, make the form encapsulate the whole table.
Then on submit you can do something like:
foreach ($_POST as $key => $value) {
//Delete $key (the name) where $value == 1
}
Your approach is fine if you want to access the hidden fields through jQuery at a given point but once you submit the form and lose the DOM, the PHP processing page will have no way to relate the selected checkboxes with the hidden fields as there is no consistent naming scheme.
One approach would be to use the loop counter to suffix the two in order to pair them up:
<input type="checkbox" id="radioselect_<?= $i ?>" title="Mark this video for deletion" value="1" />
<input type="hidden" id="video_name_<?= $i ?>" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
This would be good if you want to relate more than the two fields. Otherwise, you could just use the video_name as the value of the checkbox, as Ing suggested.