How to pair the values of these two arrays in PHP? - php

I have a table with some items on it and each row has a checkbox and a textarea. When I pres submit I want to take the values of the textareas ONLY for the respective checked checkbox and NOT for the ones that aren't checked even if they have textareas with some content.
<form method="post">
<?php if (!empty($arr_devices)) { ?>
<?php foreach ($arr_devices as $device) : ?>
<tr>
<td>
<input type="checkbox" name="devices[]" value="<?php echo $device["id"].$dev_comment ?>">
<td>
<td>
<div class="input-group">
<textarea name="dev_comment[]" placeholder="comment" rows="1" cols="50"><?php echo $dev_comment; ?></textarea>
</div>
</td>
</tr>
<?php endforeach; ?>
<?php } ?>
<input class="btn" type="submit" name="submit" value="Report">
<form>
Printed arrays after summitted:
Device_id([0] => 790 [1] => 1140 [2] => 1142 )
Comments( [0] => sdf [1] => sdfsdfs [2] => [3] => fsdfsd [4] => )
as it is now, I am able to receive ONLY the device_id for the checked ones but ALL the values(even empty ones) for the comments when I am submitting. Why is that happening and how to fix it?

Only checked checkboxes will be submitted. You can keep the checkbox and textarea values paired by adding the same key to their name arrays. The device ID would probably work well for that.
<td>
<input type="checkbox" name="devices[<?php echo $device["id"] ?>]" value="<?php echo $device["id"].$dev_comment ?>">
<td>
<div class="input-group">
<textarea name="dev_comment[<?php echo $device["id"] ?>]" placeholder="comment" rows="1" cols="50"><?php echo $dev_comment; ?></textarea>
</div>
</td>
If the device id is not unique, you can just use the index from the foreach loop.
Then in the form handler code you can use that shared id from the checkboxes to access the comments:
foreach ($_POST['devices'] as $id => $value) {
// do something with $_POST['dev_comment'][$id]
}

Related

Not able to retrieve POST value after form POST --> PHP

i have a form with an input box which will double when clicking on add button , something like below
So it will keep on adding UTM ID, and when when i submit the form , the data should be fetched and printed using PHP , but Form gets posted but data is not passed .
So below is my code
<form method="POST" action="" class="basic-repeater" >
<select class="js-example-basic-single">
<option>Select Instance </option>
</select>
<div data-repeater-list="group-a">
div data-repeater-item>
<div class="row">
<div class="col-md-2 col-sm-12 form-group">
<label for="name">UTM ID</label>
<input type="text" class="form-control" name="name[]" id="name" placeholder="UTM Id">
<button type="submit" name="SaveModules" class="btn btn-primary" >Update</button>
</form>
<?php
if (isset($_POST['SaveModules'])){
$UTMID = $_POST['name']; // value not getting retrieved
echo "<script>console.log('Debug Objects: ".$UTMID."' );</script>";
}
?>
So Can anyone help me to figure out the issue
The code don't work because name input (name="name[]") is multiple so in php will be an array.
if you do like that you will see all work because will take the first value of array:
echo "<script>console.log('Debug Objects: ".$UTMID[0]."' );</script>";
Instead if you want multiple ids use a foreach like:
if (isset($_POST['SaveModules'])) {
$UTMID = $_POST['name']; // value not getting retrieved
foreach($UTMID as $id){
echo "<script>console.log('Debug Objects: " . $id . "' );</script>";
}
}
Another "tips" is to don't mixup like that php/js, if you need return in js use AJAX instead, or if you need to debug it use simple echo
I checked this code in local with multiple names and i got the correct array
<form method="POST" action="" class="basic-repeater" >
<div class="col-md-2 col-sm-12 form-group">
<label for="name">UTM ID</label>
<input type="text" class="form-control" name="name[]" id="name" placeholder="UTM Id">
<input type="text" class="form-control" name="name[]" id="name1" placeholder="UTM Id">
<input type="text" class="form-control" name="name[]" id="name2" placeholder="UTM Id">
<input type="text" class="form-control" name="name[]" id="name3" placeholder="UTM Id">
<button type="submit" name="SaveModules" class="btn btn-primary" >Update</button>
</div>
</form>
<?php
if (isset($_POST['SaveModules'])){
$UTMID = $_POST['name'];
print_r($_POST);
//echo "<script>console.log('Debug Objects: ".$UTMID."' );</script>";
}
?>
and i got the result in post
[name] => Array ( [0] => 12 [1] => 34 [2] => 56 [3] => 78 ) [SaveModules] => )
and if you need the array in javascript then you need to use json_encode because you can not print php array direct in console.log
echo "<script>console.log('Debug Objects: ".json_encode($UTMID)."' );</script>";
Debug Objects: ["rret","dfgdfg","dfgfg","ghvnv"] index.php:12:9
name=name[] will be an array.
$name[number] //to retrieve array values
Multiple input with same name.
You can set name=value[]
Then you can retrieve the value with.
val[0] //leads to the first value
This is sample php got implode array value
<?php
if(isset($_POST['SaveModules'])){
$VAL= $_POST['name'];
$UTMID = implode(', ',$VAL);
echo $UTMID; //output = Value1, Value2, Value3
// echo "<script>console.log('Debug Objects: ".$UTMID."' );</script>";
}
Try changing your name="name[]" to something like name="UTM" as you are looking for name[] and also requesting name
As for the multiple posts, you could add in your script that makes a new input box and add n after UTM, this would be good as you also know which box they are filling in.
Here:
<form method="POST" action="" class="basic-repeater" >
<div class="col-md-2 col-sm-12 form-group">
<label for="name">UTM ID</label>
<input type="text" class="form-control" name="UTM1" id="name" placeholder="UTM Id">
<button type="submit" name="SaveModules" class="btn btn-primary" >Update</button>
</form>
<?php
if (isset($_POST['SaveModules'])){
$UTMID = $_POST['UTM1']; // value not getting retrieved
echo "<script>console.log('Debug Objects: ".$UTMID."' );</script>";
}
?>

Fetch data from database into checkbox and get the selected values PHP [duplicate]

This question already has answers here:
getting a checkbox array value from POST
(5 answers)
Closed 3 years ago.
I am newbie in both PHP and Mysql. I have a table in Mysql named "has" which i store the physical alignments of customers . There are two attributes CustomerID and PyhsicalAilmentName . In sign up screen i want user to select them in a checkbox. I am able to fetch the phsical alignments from database into checkbox with this form code.
<form action="includes/signup.inc.php" style="border:1px solid #ccc;width: 50%;margin: 0 auto" method="post" >
<div class="container" >
<h1>Sign up</h1>
<p>Please fill in this form to create an account.(Your username should start with "C_")</p>
<hr>
<input type="text" name="username" placeholder="Name">
<input type="text" name="user_last_name" placeholder="Last Name">
<input type="text" name="uid" placeholder="Username">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd-repeat" placeholder="Repeat Password">
<input type="text" name="user_weight" placeholder="Weight(in terms of kilogram)">
<input type="text" name="user_length" placeholder="Length(in terms of cm)">
<input type="text" name="user_age" placeholder="Age">
<p> Phsical Alignments</p>
<?php
$sql = "select Name from physical_ailment";
$result = mysqli_query($conn,$sql);
$i = 0;
while($db_row = mysqli_fetch_array($result)){
?>
<input type="checkbox" name="check_list[]"> <?php
echo $db_row["Name"]; ?> <br>
<?php
$i++; }
?>
<select name="selected_mem_type" >
<?php
$sql = "select Name from membership_type";
$result = mysqli_query($conn,$sql);
$i = 0;
while($DB_ROW = mysqli_fetch_array($result)){
?>
<option>
<?php echo $DB_ROW['Name']; ?>
</option>
<?php
$i++;} ?>
</select>
<input type ="text" name="user_card_no" placeholder="Credit Card No">
<input type="date" name="user_card_expire_date" placeholder="Expire Date of Card">
<button type="submit" class="signupbtn" name="signup-submit"> Signup </button>
<button type="submit" class="signupbtn" name="home-submit"> Home </button>
</div>
</form>
Problem is when i intended to get the selected ones with $_POST['check_list']via foreach loop it prints "on" according to number of selected checkboxes. If user selects 3 checkboxes in $_POST['check_list'] there are 3 elements which is "on" . When I select 2 things lets say , and print the $_POST['check_list'] with print_r it outputs Array ( [0] => on [1] => on [2] => on )
I search a lot but couldn't manage to find solution. Appreciate any help thank you for interest.
If you don't supply a value attribute to your checkbox in your HTML, it will default to on in most browsers to let you know it had been checked.
So if you're making checkboxes asking people to check their 3 favorite fruits.
<input type="checkbox" name="check_list[]"> Banana <br>
<input type="checkbox" name="check_list[]"> Apple <br>
<input type="checkbox" name="check_list[]"> Orange <br>
If all 3 are checked, you will have Array ( [0] => on [1] => on [2] => on )
Now if you add the value attribute
<input type="checkbox" name="check_list[]" value="banana"> Banana <br>
<input type="checkbox" name="check_list[]" value="apple"> Apple <br>
<input type="checkbox" name="check_list[]" value="orange"> Orange <br>
If all 3 are checked you'll have :
Array ( [0] => banana [1] => apple [2] => orange )
You can read more about that here : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#Value

Multiple option select form

I have created a HTML form where a user can enter his availability (which day of week). The form has a button to add new users so at the end I will have multiple DIVs for users, hence I have USER_DOW with two dimensions USER_DOW[][].
<div id="user1" class="user" >
<div class="name">
<label>Name</label>
<input type="text" name="USER_Name[]">
</div>
<div>
<label>Day of Week</label>
<select multiple id="USER_DOW" name="USER_DOW[][]" size='7'>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
<option value="Sat">Saturday</option>
<option value="Sun">Sunday</option>
</select>
</div>
</div>
I'm having issues accessing the elements in the PHP
foreach($USER_Name as $a => $b){
echo $a+1;
echo $USER_Name[$a];
echo "Number of selected days for user " + count($USER_DOW);
foreach($USER_DOW as $c => $b){
echo $USER_DOW[$c][$a];
}
}
At the moment, if I add 2 users, one selecting Wed.& Sun. and the second only Mon., what I get is three days (count) for both users and on the first user all three are printed (Wed, Sun, Mon) while for the second nothing.
Any idea? Have I misunderstood the keys in the arrays?
The names of input elements of a form are passed as written, without any interpretation.
So, in this example:
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<?php if( count($_GET) ): ?>
<pre><?php var_dump($_GET); ?></pre>
<?php endif; ?>
/* FORM #1 */
<form action="test.php">
<input type="text" name="txt[0]" value="One">
<input type="text" name="txt[1]" value="Two">
<input type="submit" name="action" value="Test">
</form>
/* FORM #2 */
<form action="test.php">
<input type="text" name="txt[]" value="One">
<input type="text" name="txt[]" value="Two">
<input type="submit" name="action" value="Test">
</form>
/* FORM #3 */
<form action="test.php">
<input type="text" name="txt[][]" value="One">
<input type="text" name="txt[][]" value="Two">
<input type="submit" name="action" value="Test">
</form>
<?php
?>
</body>
</html>
The generated URLs are:
/* FORM #1 */ test.php?txt[0]=One&txt[1]=Two&action=Test
/* FORM #2 */ test.php?txt[]=One&txt[]=Two&action=Test
/* FORM #3 */ test.php?txt[][]=One&txt[][]=Two&action=Test
(rawurldecoded for clarity)
When process $_GET/$_POST variables, PHP try to interpreter it, so in the first and second forms, the result is the same:
Array
(
[txt] => Array
(
[0] => One
[1] => Two
)
[action] => Test
)
But, in form #3, the result is:
Array
(
[txt] => Array
(
[0] => Array
(
[0] => One
)
[1] => Array
(
[0] => Two
)
)
[action] => Test
)
because PHP increment first-level key, but not the deeper key.
If you expectation is to increment the deeper array, you have to specify first-level key in the form.
Something like:
<input type="text" name="txt[1][]" value="One">
<input type="text" name="txt[1][]" value="Two">
or, if code-generated, like:
<input type="text" name="txt[<?php echo $SomeVar; ?>][]" value="One">
<input type="text" name="txt[<?php echo $SomeVar; ?>][]" value="Two">
<?php
var_dump($_POST);
function do_form($index) {
?>
<div id="user<?= $index ?>" class="user" >
<div class="name">
<label>Name</label>
<input type="text" name="USER_Name[<?= $index ?>]">
</div>
<div>
<label>Day of Week</label>
<select multiple id="USER_DOW" name="USER_DOW[<?= $index ?>][]" size='7'>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
<option value="Sat">Saturday</option>
<option value="Sun">Sunday</option>
</select>
</div>
</div>
<?php
}
?>
<form method="POST">
<?php do_form(1); do_form(2); ?>
<input type="submit">
</form>
Sample output after submit:
array (size=2)
'USER_Name' =>
array (size=2)
1 => string 'foo' (length=3)
2 => string 'bar' (length=3)
'USER_DOW' =>
array (size=2)
1 =>
array (size=1)
0 => string 'Mon' (length=3)
2 =>
array (size=2)
0 => string 'Mon' (length=3)
1 => string 'Tue' (length=3)

Getting post data from selected rows in a table

I've been trying to think this through, but can't seem to figure out how to get data from only one selected row in a table. I have a table that I am populating with php, lets say it has a name, tn, address in one column. I was thinking of putting a checkbox at the end of the column and having the user check it if the data can be sent to the server. Now, if I do that how do I get the data from that column? I could use javascript to populate the table also, but I'm still stuck with the same problem of how to get the data from the column to update my tables.
<?php
foreach (defaultPay() as $key => $values):
foreach ($values as $value):?>
<tr>
<td>
<label for="number"></label><input type="text" id="number" name="empNum" value="<?= $value['empNum']; ?>">
</td>
<td>
<label for="name"></label><input type="text" id="name" name="empName" value="<?= $value['empName']; ?>">
</td>
<td>
<label for="stdHrs"></label><input type="text" step="any" id="stdHrs" name="stdHrs" value="<?= $value['unitRate']; ?>">
</td>
<td>
<label for="uniRate"></label><input type="text" step="any" id="uniRate" name="uniRate" value="<?= $value['rate']; ?>">
</td>
<td>
<label for="salRate"></label><input type="text" step="any" id="salRate" name="salRate" value="<?= $value['salary']; ?>">
</td>
<td>
<label for="gross"></label><input type="text" step="any" id="gross" name="gross" value="<?= $value['gross']; ?>">
</td>
</tr>
<?php }
} ?>
I suppose you are populating the table from some kind of php array. If you don't have unique identifier, each element have index in array. You could use that index and set it as checkbox value.
For example:
<input type="checkbox" value="<?php echo $index; ?>" />
where $index is unique table index. After form submition you will have selected indexes of the table. Remember to keep te table order the same.
If only one row will be selected by the user a button within a form will do. Forms and hidden input does not affect page rendering. Just make the form CSS display:inline; The whole form can be put in one small <td> table element regardless of how much data you want to store in multiple <input type="hidden"/> tags.
'<tr><td><form action="save.php" method="post" ><input type="hidden" name="id" value="1234" /><input type="hidden" name="col1" value="' . $row[1] . '" /><input type="hidden" name="col2" value="' . $row[2] . '" /> <button type="submit">Save</button></form></td><td>Text describing the row</td></tr>';
The first column in the table has a "Save" button which submits the data.

PHP Codeigniter Undefined Offset Error

I am building a Codeigniter shopping cart. On the cart details page I have a form input field allowing the user to type in the quantity required of a product, and a submit button to post the information to the update function.
When there is just one item in the cart, when updating the quantity everything works as it should. However, when there is more than one item, changing the quantity of an item and clicking submit results in a ‘Undefined Offset 1: error on the following code in the Model (specifically the two lines within the array) :
function validate_update_cart()
{
$total = $this->cart->total_items();
$item = $this->input->post('rowid');
$qty = $this->input->post('qty');
for($i=0;$i < $total;$i++)
{
$data = array(
'rowid' => $item[$i],
'qty' => $qty[$i]
);
$this->cart->update($data);
}
}
This is the View code to which the above refers:
<form action="<?php echo base_url(); ?>home/update" method="post">
<div><input type="hidden" name="rowid[]" value="<?php echo $item['rowid']; ?>"/></div>
<div><input type="text" name="qty[]" value="<?php echo $item['qty']; ?>" maxlength="2" class="chg-qty"/></div>
<div><input type="submit" value="update" class="update-quantity"/></div>
</form>
And this is the Controller:
function update()
{
$this->products_model->validate_update_cart();
redirect('cart');
}
Please can anyone explain why this is happening?
Many thanks,
Matt
instead of
for($i=0;$i < $total;$i++)
use this
for($i=0;$i < count($item);$i++)
I had the same issue; I'm pretty sure the issue is in the shopping cart view
section. The hidden field isn't inside the foreach{} statement - that's why
you can edit the quantity when you have one product in your shopping cart, but
when you add another product can't edit the product. Here's a chunk of code
that worked for me.
<?php if ($this->cart->total_items()!=0) :?>
<div id="cart">
<?php if ($cart=$this->cart->contents()) :?>
<table>
<caption>Shopping Cart</caption>
<thead>
<th>Item Name</th>
<th>Option</th>
<th>Price</th>
<th>Qty</th>
<th></th>
</thead>
<?php foreach ($cart as $item): ?>
<tr>
<td><?=$item['name'];?></td>
<td>
<?php
if ($this->cart->has_options($item['rowid'])) {
foreach ($this->cart->product_options($item['rowid']) as $option => $value) {
echo $option.": <em> ".$value." </em>";
};
};
?>
</td>
<td>$<?=$item['subtotal'];?></td>
<?=form_open('index.php/shop/update_cart'); ?>
<td>
<?=form_input(array('name' => 'qty[]', 'value' => $item['qty'], 'maxlength' => '2', 'size' => '2')); ?>
</td>
<td class="remove"><?=anchor('index.php/shop/delete/'.$item['rowid'],'X','class="remove"');?></td>
<td> <?=form_hidden('rowid[]', $item['rowid']); ?></td>
</tr>
<?php endforeach;?>
<tr class="total">
<td colspan="2"> <strong>Total</strong> </td>
<td>$<?=$this->cart->total();?></td>
</tr>
<tr>
<td><?php echo form_submit('submit', 'Update your Cart'); ?></td>
<!-- When you want to empty your cart using ajax, add 'class="empty"' as a third parameter. -->
<td><?=anchor('index.php/shop/empty_cart', 'Empty Cart', 'class="empty"');?></td>
<?=form_close();?>
</tr>
</table>
<?php endif;?>
</div>
<?php endif;?>
I believe that your problem is that you need to have
<form action="<?php echo base_url(); ?>home/update" method="post">
<div><input type="hidden" name="rowid[]" value="<?php echo $item['rowid']; ?>"/></div>
<div><input type="hidden" name="rowid[]" value="<?php echo $item['rowid']; ?>"/></div>
<div><input type="text" name="qty[]" value="<?php echo $item['qty']; ?>" maxlength="2" class="chg-qty"/></div>
<div><input type="text" name="qty[]" value="<?php echo $item['qty']; ?>" maxlength="2" class="chg-qty"/></div>
<div><input type="submit" value="update" class="update-quantity"/></div>
</form>
Namely, the 2 entries for the rowid and qty.
This link provides examples of using both standard and associative arrays with HTML inputs.
EDIT based on OP feedback:
This was the example I was referring too:
<label><input type="checkbox" name="choice[]" value="1"/> 1</label>
<label><input type="checkbox" name="choice[]" value="2"/> 2</label>
<!-- etc... -->
// meanwhile, on the server...
$choice = $this->input->post('choice');
print_r($choice); // Array ( [0] => 1 [1] => 2 );
Another example:
<form method="post" action="">
<input maxlength="30" name="friend[]" size="30" type="text" />
<input maxlength="30" name="friend[]" size="30" type="text" />
<input maxlength="30" name="friend[]" size="30" type="text" />
<input type="submit" value="Submit" />
</form>
// ***** Server-Side PHP: *****
// Loop through the friend array
foreach ($_POST['friend'] as $value) {
if ($value) { echo $value."<br />"; }
}
Notice where the examples are using an input with the same "blah[]" for each value they expect to come back in the array. In your code, you have one rowid[] and one qty[] input in your view. For a single element this will work b/c you have one element defined in the array. when you have 2 items and you apparently are updating the total items variable to represent the correct number of items but then loop through trying to access the second element (i.e. 1) in each array which does not exist which is why you're getting "Undefined Offset 1" error.

Categories