I am trying to allow my users to update quantities in the database, by providing them some input fields, I know that the sql update query is perfect, because if i DONT use the foreach loop, it will submit and update the last textfield only.
But I need the foreach loop so it will loop through all the textfields and update them all in the database. Can somebody please help me figure out why it's not updating with this foreach loop? Lots of thanks in advance :)
foreach($_POST['items'] as $p=>$q)
{
// working sql code is in here.
}
And the fields are dynamically generated like so:
$ct->data[$key][0]='<input type="text" value="'.$ct->data[$key][0].'" name="product" />';
$ct->data[$key][1]='<input type="text" value='.$ct->data[$key][1].' id="qty" name="items[' . $ct->data[$key][1] . ']" />';
$ct->data[$key][2]='<input type="submit" value="Update Item">';
$ct->data[$key][3]='<p name="price">'.$ct->data[$key][3].'</p>';
You should ALWAYS check if a variable exists. That's no more that normal and should have been lession 1.
You can't iterate over $_POST['items'] if $_POST['items'] doesn't exist (obviously). So you have to check if the form has been submitted.
One way is:
if ( isset($_POST['items']) ) {
// foreach ( $_POST['items'] ....
}
I always like to be on the safe side and check for type as well:
if ( isset($_POST['items']) ) {
// form submitted at least
if ( is_array($_POST['items']) ) {
// and it's an array as it should be
foreach ( ....
}
}
POST variables are never set in a GET request, so doing the foreach first time on a page is useless. That's what the check is for: 'is the form submitted and do the necessary post vars exist?'
What values are you seeing?
foreach($_POST['items'] as $p=>$q) {
print "$p: $q\n";
}
The name of the items input field should just be items[].
So:
# Good
$ct->data[$key][1]='<input type="text" value='.$ct->data[$key][1].' id="qty" name="items[]" />';
# Bad
$ct->data[$key][1]='<input type="text" value='.$ct->data[$key][1].' id="qty" name="items[' . $ct->data[$key][1] . ']" />';
Related
I am new to PHP and the project I am working on is a codeigniter php form writing back to a FileMaker database.
The checkboxes should be populating as a list field.
Here is my form
<input name="fieldname[]" value="value1"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value1
<input name="fieldname[]" value="value2"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value2
There are about 7 checkboxes.
I assume that I have to setup a foreach loop to get it to go thought to FileMaker's field, but unsure how to do that.
If I take away the array, the last one selected goes through to the layout.
Any help would be great.
Presumably, these values mirror a valueList back in FileMaker. If so, it's best to assign the valueList to a variable:
$values = $layout->getValueList('pizzaToppings');
And use that in your for loop:
foreach($values as $value)...
In your if(isset()) block, post a return-delimited array to FileMaker:
// value(s)!
if ($_POST['fieldname']) {
$valueArray = implode("\r", $_POST['fieldname']);
}
// pass the array to setField()
$record->setField('filemakerField', $valueArray);
I worked it out. To enter checked boxes into a return separated list:
View:
At the top of the section with the checkboxes
<?php $join->fieldname = explode("\n", $join->fieldname); ?>
// The actual input in the form
<input name="fieldnameXX[checkboxValue]" value="value" <?php echo (in_array('value', set_value('fieldname[value]', $join->fieldname)) ? ' checked="checked"': '')?> type="checkbox" class="form-check-input" > Value
Factory:
$fieldnameZZ = $data['fieldnameXX'];
$data['fieldnameXX'] = FALSE;
unset($data['fieldnameXX']);
$sacraments = implode("\n", $fieldnameZZ);
$data['fieldname'] = $fieldnameZZ;
I'm not sure if this is the best way to have done it, but it works.
$ids=implode(",", $_REQUEST["fieldname"]);
$result3=mysqli_query($dbh,'SELECT* FROM excel_tenant WHERE ID IN ("' .
$ids . '") AND
ManagerID = "'.$_SESSION["ManagerID"].'" ORDER BY ID DESC ') or
die(mysqli_error($dbh));
I'm written a PHP program to display a tab delimited file. The purpose of this is to allow the user to views the rows and select which ones they want by checking the checkbox given in the row for each record. After they hit submit I have a PHP program to display the values, but the problem is only the last row's ID is being passed. However, when the user hits the SUBMIT button I can see all the values for the rows checked:
process_form.php?download=5108&download=5110&download=5114
How should I parse this in process_form.php? I've done a var_dump of $_POST and also
$_REQUEST but it only shows the last value which is 5114. I kind of understand the problem, most of the time in forms programmers only get one value per input field, but what happens when there are many records? It doesn't seem they should all have their own unique 'name'.
<td align=center><input type="checkbox" name="download" value="<?php echo $row['ID']; ?>"></td>
I'm doing something wrong here, but I'm not sure what. Is there a way to pass an array (I'm guessing) of IDs? Or should I be looking at parsing the URL of ?download=5108&download=5110&download=5114 because it has all the values I need there? If so, how do I do that? Thanks!
This is my solution:
<td align=center><input type="checkbox" name="download[]" value="<?php echo $row['ID']; ?>"></td>
Notice that download is now download[], thus creating an array to be passed to the PHP program to process the form.
Then using this demo PHP code I was able to get access to the array:
$my_array = ($_REQUEST["download"]);
print_r($my_array);
echo "<P>";
foreach ($my_array as $value)
{
echo $value . "<BR>";
}
I'd rather use your rowID to identify the name of <input> instead of the value.
<td align=center><input type="checkbox" name="download_<?php echo $row['ID']; ?>" value="1"></td>
Then you can process your request array like:
foreach( $_REQUEST as $key => $value ) {
if( preg_match('/^download_([0-9]+)$/', $key, $reg ) {
$rowId = $reg[1]; // Your row ID
$isChecked = $value; // State of checkbox
}
}
The row ID is parsed from variable name using regexp.
EDIT:
As mentioned in comments, this is not the simplest way to read an array of checkboxes. The simpliest is to name checkboxes download[] and parse this array in PHP then.
However, this is more universal, for example when you need to get array of input texts instead of checkboxes.
I have issues with creating an array and storing the info, I have a table with data that could be infinite in its number, a user will then select some options which will determine which of these values they can select (which again is an infinite number), these choices are then presented into a checkbox where i use this code
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details" value="'.$invoice_details.'"/>';
}
?>
So this should search through the options they previous choose, and sorts them into an array and then into checkboxs, but when i store the information is just saves the last box checked, I cant change the value of each input EG
echo '<input type="checkbox" name="invoice_details[value1]"
echo '<input type="checkbox" name="invoice_details[value2]"
Because I don't know how many values/checkboxes there will be.
I have also tried this
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details[] = $detailsline->details_line;
echo $invoice_details[];
echo '<input type="checkbox" name="invoice_details[]" value="'.$invoice_details.'"/>';
}
?>
Changing the
$invoice_details
to
$invoice_details[]
but this will just store a value "Array" in my database and not the actual values.
Please can anyone help me?
Ian
Okey I think You should Try this:
<?php
$i=0;
foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details[$i]" value="'.$invoice_details.'"/>';
$i++;
}
?>
Try this
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details[]" value="'.$invoice_details.'"/>';
}
?>
Use <input type="checkbox" name="invoice_details[]">
In your code you can use serialize($invoice_details) for saving into DB and when using - unserialize($field_from_db).
First function returns string, so you can save it as string field, second function get the string and returns the whole array, so you can work with it.
but this will just store a value "Array" in my database and not the actual values.
think you tried to store Array as string so got that value
So may be needed to use implode/serialize/json_encode (Array) to store data?
Literally saying code $invoice_details[] = $detailsline->details_line; means take property details_line of an object $detailsline and insert its value as new element in array $invoice_details. Are you sure it is what you want?) Also I suppose that $detailsline is an array, but not the object (you trying to operate it as an object)
This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}
How can I display this value in the loop ?
echo '<input type="hidden" name="eg_payamt_'.$i.'" id="amount_post_'.$i.'" value="">';
this code is being passed into next code by POST
On the next page,
Could it be like this ?
foreach($_POST["eg_payamt_"] as $key => $payamt)
{
echo "eg_payamt_$key => $payamt\n <br>";
}
I don't see any results,
Do you guys have any ideas ??
You have to change the name of the input element -- all input elements like this will have the same name:
<input type="hidden" name="eg_payamt[]" value="whatever" />
And then when you access $_POST['eg_payamt'] it will already be an array, so your code will work almost as-is (you need to lose a couple of underscores).