PHP get the table data row input value using loop - php

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.

Related

How to get selected checkbox index in php

I have a checkbox as follows,
<tr>
<td>
<input type="checkbox" checked="checked" name="feegroupid[]" class="fee_checkbox" value="<?php echo $fee_value->fee_groups_feetype_id ?>">
</td>
<td>
<input type="text" name="actual_pay[]" class="form-control modal_amount actual_pay" id="amount" value="<?php echo $feetype_balance; ?>">
</td>
</tr>
And my PHP function if the checkbox row is selected,
foreach($_POST['feegroupid'] as $index => $selected) {
echo $index;
$actualPayment = $_POST['actual_pay'][$index];
}
I have two rows with checkbox,
Here the echo $index is displaying only the first row index 0 if i select the second row (whose index is 1).
But both is selected (ie.checked), it is showing both index as 0,1 respectively.. But when we uncheck one checkbox(say first row with index 0 is unchecked), it is showing the 0 only but checked index is 1.
I am in the need to get the value of another input box with name actual_pay[] based on the checked box index..
How to get the respective checked box index instead of the first row index while changing checkbox?
Attached image has a button click to pay which should send the checked box index (ie, second box is checked and its index is 1).
Something like this should work:
<tr>
<td>
<input type="checkbox" checked="checked" name="feegroupid[]" class="fee_checkbox" value="<?php echo $fee_value->fee_groups_feetype_id; ?>">
</td>
<td>
<input type="text" name="ap_<?php echo $fee_value->fee_groups_feetype_id; ?>" class="form-control modal_amount actual_pay" id="amount" value="<?php echo $feetype_balance; ?>">
</td>
</tr>
PHP:
if (isset($_POST['feegroupid'])) {
foreach ($_POST['feegroupid'] as $k => $v) {
if (isset($_POST['ap_' . $v])) {
echo $_POST['ap_' . $v]; //$actualPayment
} else {
echo 'Not found for item: ap_' . $v;
}
}
}

PHP handling combined checkboxes and select boxes

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.

Looping through an array of checkbox

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>

Tie two inputs together (text & hidden)?

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.

PHP - How to submit a form containing input fields that point to different MySQL rows

I am setting up a form using this PHP that loops through all records a user may have:
<?php foreach ($items as $row): ?>
<tr>
<td>
<?php echo form_hidden('id', $row->id); ?>
</td>
<td>
<?php echo '<strong>' . $row->name . '</strong>'; ?>
</td>
<td>
<?php echo form_input('number', $number); ?>
</td>
<td>
<?php echo form_input('registry', $registry); ?>
</td>
<td>
<?php echo form_checkbox('OK', $ok, $ok); ?>
</td>
</tr>
<?php endforeach; ?>
This gives me a form with the following look:
The idea here is that each row belongs to a unique ID/row in the database, and I would like to allow the user to edit all on the same page/form, using a single submit button.
What would be the best way of implementing this?
When this data is submitted, there should be a way of looping through each packet of information (from each user) in my controller. Would this be done via ajax/json?
This does not use codeigntier, but you should be familiar with the general technique before attempting to use CI to shortcut this process. Codeigniter will help you with rendering the form elements, performing validation, escaping your input and performing your query - but it will only help you (do anything) if you understand the basic principles involved. Hope this helps
MARKUP
<form action="/process.php">
<div>
<h2>GORDON</h2>
<input type="text" name="user[1][number]" /> <!-- The number corresponds to the row id -->
<input type="text" name="user[1][registry]" />
<input type="checkbox" name="user[1][ok]" value="1" />
</div>
<div>
<h2>ANDY</h2>
<input type="text" name="user[242][number]" />
<input type="text" name="user[242][registry]" />
<input type="checkbox" name="user[242][ok]" value="1" />
</div>
<div>
<h2>STEWART</h2>
<input type="text" name="user[11][number]" />
<input type="text" name="user[11][registry]" />
<input type="checkbox" name="user[11][ok]" value="1" />
</div>
<input type="submit" />
PHP
$users = $_REQUEST['user'];
foreach ($users as $rowId => $info){
// YOU SHOULD MAKE SURE TO CLEAN YOUR INPUT - THIS IS A GUESS AT WHAT YOUR DATA TYPES MIGHT BE
$id = (int) $rowId;
$number = (int) $info['number'];
$registry = mysql_real_escape_string($info['registry']);
$ok = (int) ($info['ok']);
$q = "UPDATE user SET number = $number, registry = '$registry', ok = $ok WHERE id = $id";
mysql_query($q);
// You may want to check that the above query was sucessful and log any errors etc.
}
There's no need to use ajax mate.
For each put a hidden input with the ID of the row in this format:
<input type="hidden" name="id[<?= $row->id ?>]" value="<?= $row->id ?>" ?>
Do the same for each element in the tr, i.e. name them as
name="number[<?= $row->$id ?>]"
name="registry[<?=$row->$id ?>]"
name="ok[<?=$row->$id ?>]"
and once you post the FORM you can iterate each row with:
foreach ($_POST['id'] as $key => $value) {
echo $_POST['name'][$key];
}
You need to set up input-names as array-names, so you will send the whole form and may iterate over the entries.
e.g.
<?php
echo form_input('userdata[' . $row->id . '][number]', $number);
?>
which would possibly create an
<input name="userdata[1][number]" />
(I don't know where those form-functions came from…)
This will result in an array $_POST['userdata'] which may be iterated via:
foreach($_POST['userdata'] as $userId => $userInputFields)
{
$user = new User($userId);
$user->number = $userInputFields['number'];
// …
}

Categories