Array not carrying data forward - php

I have a form with 10 similar rows of data required. The form collects product codes, descriptions and quantities. I loop through 10 rows and use arrays to collect the information.
$code = array();
$description = array();
$quantity = array();
<?php
for($i=0; $i<10; $i++){
?>
<div class="quote-row">
<div class="quote-id">
<?php echo $i+1; ?>
</div>
<div class="quote-code">
<input type="text" class="quotecode" name="<?php echo $code[$i]; ?>" />
</div>
<div class="quote-description">
<input type="text" class="quotedescription" name="<?php echo $description[$i]; ?>" />
</div>
<div class="quote-quantity">
<input type="text" class="quotequantity" name="<?php echo $quantity[$i]; ?>" />
</div>
</div>
<?php
}
?>
On the following page, I then use $_POST['code'], $_POST['description'], $_POST['quantity'] to carry the data forward and attempt to use it.
My issue is that the data doesn't appear to be arriving?
Using the for loop, will I still be able to submit the form and take all the data forward?
Hope this is as informative as possible, thanks!

You are giving value of array in name attribute. Your array is empty so your name is empty too.
Try this:
<?php
for($i=0; $i<10; $i++){
?>
<div class="quote-row">
<div class="quote-id">
<?php echo $i+1; ?>
</div>
<div class="quote-code">
<input type="text" class="quotecode" name="code[]" />
</div>
<div class="quote-description">
<input type="text" class="quotedescription" name="description[]" />
</div>
<div class="quote-quantity">
<input type="text" class="quotequantity" name="quantity[]" />
</div>
</div>
<?php
}
?>
name[ ] format automatically make your data an array.

The key to use with the $_POST array is whatever you put in the name="" attribute. Based on the code you provided the names aren't code, description, and quantity but whatever the actual codes, descriptions, and quantities of the items are. You probably want to do this instead:
$code = array();
$description = array();
$quantity = array();
<?php
for($i=0; $i<10; $i++){
?>
<div class="quote-row">
<div class="quote-id">
<?php echo $i+1; ?>
</div>
<div class="quote-code">
<input type="text" class="quotecode" name="code[]" value="<?php echo $code[$i]; ?>" />
</div>
<div class="quote-description">
<input type="text" class="quotedescription" name="description[]" value="<?php echo $description[$i]; ?>" />
</div>
<div class="quote-quantity">
<input type="text" class="quotequantity" name="quantity[]" value="<?php echo $quantity[$i]; ?>" />
</div>
</div>
<?php
}
?>

There are several places where code needs to be updated to work as you expect it.
The most important being that the inputs are using the wrong attributes to store the name and value.
For example, the input element needs to look something like this for each of your inputs:
<input type="text" class="quotecode" name="code[]" value="<?php echo $code[$i]; ?>" />
After, adding a submit button and the surrounding form tags you can then proceed to inspect the variables in next page using PHPs $_POST or $_GET variables.

Related

Store data obtained using foreach loop from view into the database using CodeIgniter

I am trying to store the values obtained from the form into the database. I am stuck where I do not know how to obtain the values individually from foreach($questions as $row) and store them into the database.
My database table has the following columns:
variantid | stepid | questionid | newquestion | radiovalues | description
When I click on save, I am trying to save all the details obtained from the view into the database. every value obtained with each loop of foreach($questions as $row) needs to get stored in a new row. I think I should be using insert_batch, but I do not know how I can put all the data into the array.
How can I proceed with this? The following is the code that I have written. I have not written anything in model as I am stuck.
<form id="theform">
<label for="variants">Variants:</label><br>
<?php
foreach($variants as $row)
{?>
<div class="form-group">
<input type="radio" name="variants[]" checked="true" id="variants" value="<?php echo $row->variantid ?>"/><?php echo $row->variantname ?><br/>
<?php }
?>
<div id='steplist'>
<?php
foreach($substeps as $row){
?>
<div id='img_div'>
<input type="radio" name="stepid[]" checked="true" id="stepid<?php echo $row->stepid; ?>" value="<?php echo $row->stepid; ?>"/><?php echo $row->stepname ?><br/>
</div>
<?php
foreach($questions as $each){
?><br><br>
<input type="text" name="questions[]" id="questions<?php echo $each->questionid; ?>" value="<?php echo $each->questionname; ?>" readonly/><br/>
<input type="hidden" name="questionid[]" id="questions<?php echo $each->questionid; ?>" value="<?php echo $each->questionid; ?>"/>
<a id="addq">Add question</a>
<input type="text" class="form-control" name="newquestion[]" style="font-weight:bold;width:100%;height:5%" id="new_questions<?php echo $each->questionid; ?>" /><br>
<div class="radio" id="answer">
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="no" required>no</label>
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="probably no" required>probably no </label>
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="unknown" required>unknown</label>
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="probably yes" required>probably yes</label>
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="yes">yes</label>
</div>
<textarea name="question1_text[]" id="description<?php echo $each->questionid; ?>" rows="3" cols="73"></textarea><br>
<?php
}
?>
<?php
}
?>
</div>
</form>
<input type='button' value='Save' class='save' id='save' />
<script>
$(document).ready(function(){
$("#save").click(function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:"<?= base_url() ?>index.php/task/perform",
data:$('#theform').serialize(),
success:function(response){
alert(response);
}
});
});
});
This is my controller:
public function perform(){
var_dump($_POST);
$variantid = $this->input->post('variants');
$stepid = $this->input->post('stepid');
$questionid = $this->input->post('questions');
$newquestion = $this->input->post('newquestion');
$radioquestions = $this->input->post('radioquestions');
$question1_text = $this->input->post('question1_text');
$this->load->model('task_model');
$result= $this->task_model->performdata();
if($result){
echo "Data saved successfully";
}
}
Update
Thank you for the quick reply. I changed the code according to the suggestion. How can I get these values into the controller and send them into the database?
The HTML inside the foreach is invalid as it is missing a closing div tag and your input does not have the correct name attribute, for multiple inputs you should use variants[] and not the same ID. Do it in this manner:
<?php foreach ($variants as $row) { ?>
<div class="form-group">
<input type="radio" name="variants[]" checked="true" class="variants" value="<?php echo $row->variantid ?>"/><?php echo $row->variantname ?><br/>
</div>
<?php } ?>

MultiDimentional array in $_POST, checklist form

I am trying to make a form that mocks a checklist of sorts. Let me explain:
I have a number of jars. Inside each jar are a number of jelly beans. Each bean is different. I can have any number of jars and beans. I want to create a form as so:
public static function getForm($oData) {
<form action="<?= esc_url($_SERVER["REQUEST_URI"]); ?>" method="post" id="CountForm">
<fieldset>
<?php foreach ($aJars as $oJar) {
$aJellyBeans = JellyBeans::getJellyBeansBase($oJar->Jar_ID); ?>
<p><?= $oJar->JarName; ?></p>
<?php foreach ($aJellyBeans as $oJellyBean) { ?>
<input type="checkbox" name="?" id="CountedFor" value="1">
<input type="hidden" name="?" id="AccountedFor_ID" value="<?= $oData->AccountedFor_ID; ?>">
<input type="hidden" name="?" id="Jar_ID" value="<?= (($oData->Jar_ID) ? $oData->Jar_ID : $oJellyBean->Jar_ID); ?>">
<input type="hidden" name="?" id="JellyBean_ID" value="<?= (($oData->JellyBean_ID) ? $oData->JellyBean_ID : $oJellyBean->JellyBean_ID); ?>">
<label for="Notes">Notes</label>
<textarea name="?" id="Notes" cols="30" rows="5" wrap="soft" placeholder=" "><?= $oData->Notes; ?></textarea>
<?php } ?>
<?php } ?>
<input type="submit" name="Submit" id="Submit" value="<?= (($oData->AccountedFor_ID) ? 'Update' : 'Add' ) ?>">
</fieldset>
</form> <?php
}
When $_POST gets sent it goes to a class function that handles writing to the DB. The function will look at the name field and use that as the column name.
protected function CreateAccountedFor($aData) {
//Process provided data
foreach ($aData as $sKey => $eValue) {
$aSQL[$sKey] = $eValue;
}
}
I want to create a list of each jelly bean, sorted by jar, and be able to check each off as "accounted for" and submitted in one go.
I know the name field is what $_POST looks at, but is there a way to manipulate that property to form an array like:
["AccountedFor"]=>
[0]=>
["AccountedFor_ID"]=> "..."
["Jar_ID"]=> "..."
["JellyBean_ID"]=> "..."
[1]=>
["AccountedFor_ID"]=> "..."
["Jar_ID"]=> "..."
["JellyBean_ID"]=> "..."
You can assign the array values in the input name, use a for loop to count which iteration you're currently on.
If you're generating multiple of these inputs you're going to have invalid code, the id for each input will be repeated, maybe use classes instead or ditch them altogether.
<?php for ($i = 0; $i < count($aJellyBeans); $i++) { ?>
<input type="checkbox" name="AccountedFor[$i][CountedFor]" id="CountedFor" value="1">
<input type="hidden" name="AccountedFor[$i][AccountedFor_ID]" id="AccountedFor_ID" value="<?= $oData->AccountedFor_ID; ?>">
<input type="hidden" name="AccountedFor[$i][Jar_ID]" id="Jar_ID" value="<?= (($oData->Jar_ID) ? $oData->Jar_ID : $aJellyBeans[$i]->Jar_ID); ?>">
<input type="hidden" name="AccountedFor[$i][JellyBean_ID]" id="JellyBean_ID" value="<?= (($oData->JellyBean_ID) ? $oData->JellyBean_ID : $aJellyBeans[$i]->JellyBean_ID); ?>">
<label for="Notes">Notes</label>
<textarea name="?" id="Notes" cols="30" rows="5" wrap="soft" placeholder=" "><?= $oData->Notes; ?></textarea>
<?php } ?>

PHP array in WHILE

I have this piece of code:
<?php
$counter = 0;
while ($row = mysql_fetch_array($bim_coupons_price)){?>
<div class="clone">
<div id="start_date_countdown">
<span>No</span>
<input id="start_datetimepicker<?php echo $counter?>" type="text" name="start_date_countdown[]" value="<?php if(isset($_POST['start_date_countdown'][0])){echo $_POST['start_date_countdown'][0];}else{echo $row['start_date_countdown'];}?>"/>
</div>
<div id="end_date_countdown">
<span>Līdz</span>
<input id="end_datetimepicker<?php echo $counter?>" type="text" name="end_date_countdown[]" value="<?php if(isset($_POST['end_date_countdown'][0])){echo $_POST['end_date_countdown'][0];}else{echo $row['end_date_countdown'];}?>"/>
</div>
<div id="price_container">
<span>Cena</span>
<input type="text" id="price_new" name="price_new[]" value="<?php echo $row['price_new']?>"/>
</div>
</div>
<div style="clear:both;"></div>
<?php $counter++; } ?>
Problem is there that this while loop will executes 3 times and I need to change $_POST['start_date_countdown'][0]) every time to $_POST['start_date_countdown'][1]), $_POST['start_date_countdown'][2]) etc...
How I can do that?
Just change $_POST['INDEX_KEY'][0] to $_POST['INDEX_KEY'][$counter]. INDEX_KEY pertains to start_date_countdown and end_date_countdown
Well u are already are using variable $counter.You can make it $_POST['start_date_countdown'][$counter]

HTML & PHP - How to make multiple forms submittable

I have the following code which loops through an array to create forms that are filled with values (which the user will be able to edit) on a single page. There are as many forms as there are loops in the array, which is always changing.
<body>
<div id="main">
<?php
foreach($articles as $item) { ?>
<div id='container'>
<form>
Title: <input type="text" name="title" size="80" value="<?php echo $item[0]; ?>">
<br>
URL: <input type="text" name="url" size="80" value="<?php echo $item[1]; ?>">
<br>
End Date: <input type="text" name="endDate" value="<?php echo substr($item[7], 14, strpos($item[7], '#') - strlen($item[7])); ?>">
<br>
<?php
if (substr($item[8], 0, 2) === 'Su'){
} else {
?>
Start Date: <input type="text" name="startDate" value="<?php echo substr($item[8], 7, 9); ?>">
<?php } ?>
</form>
</div>
<?php } ?>
</div>
</body>
Now, I want the user to have a single submit button at the bottom of the page which will submit ALL the forms on the page to MySQL database. The problem is I don't know how to do that.
I know the submit button takes the format of
<input type="submit" value="Submit">
I am assuming I need to give each form in the loop a unique name but from there I am at a loss as to what my next step should be to actually send and receive the information from these multiple forms.
Any help would be appreciated. Thanks.
You can't submit more than one form at once. What is wrong with putting all sets of <input>s into a single form?:
<body>
<div id="main">
<form>
<?php
$inpCnt = 0;
foreach($articles as $item) {
$inpCnt++; ?>
<div id='container'>
Title: <input type="text" name="title_<?php echo $inpCnt; ?>" size="80" value="<?php echo $item[0]; ?>">
<br>
URL: <input type="text" name="url_<?php echo $inpCnt; ?>" size="80" value="<?php echo $item[1]; ?>">
<br>
End Date: <input type="text" name="endDate_<?php echo $inpCnt; ?>" value="<?php echo substr($item[7], 14, strpos($item[7], '#') - strlen($item[7])); ?>">
<br>
<?php
if (substr($item[8], 0, 2) === 'Su'){
} else {
?>
Start Date: <input type="text" name="startDate_<?php echo $inpCnt; ?>" value="<?php echo substr($item[8], 7, 9); ?>">
<?php } ?>
</div>
<?php } ?>
</form>
</div>
</body>
You need to be able to define each of these inputs aswel. So I've used the loop to give each one a unique name.

Post request is not sending all variables

I have a form which consists of rows set up like:
<div class="row unit" onmouseover="this.style.background = '#eeeeee';" onmouseout="this.style.background = 'white';" onclick="if(event.srcElement.nodeName != 'INPUT' && event.srcElement.nodeName != 'SELECT' && event.srcElement.nodeName != 'TEXTAREA'){goToByScroll(event.srcElement,-160);}">
<div class="col">
<div class="select">
<input type="checkbox" id="select<?php echo $i; ?>" name="select<?php echo $i; ?>">
</div>
</div>
<div class="col name">
<p><input class="searchable" type="text" id="name<?php echo $i; ?>" name="name<?php echo $i; ?>" value="<?php echo $name; ?>"></p>
<p>Badge ID: <input class="searchable" type="text" id="badge<?php echo $i; ?>" name="badge<?php echo $i; ?>" value="<?php echo $badge; ?>" style="width: 50px;"></p>
</div>
<div class="col phone">
<p>Work: <input class="searchable" type="text" id="phone<?php echo $i; ?>" name="phone<?php echo $i; ?>" value="<?php echo $phone; ?>"></p>
<p>Cell: <input class="searchable" type="text" id="cell<?php echo $i; ?>" name="cell<?php echo $i; ?>" value="<?php echo $cell; ?>"></p>
<p>Home: <input class="searchable" type="text" id="home<?php echo $i; ?>" name="home<?php echo $i; ?>" value="<?php echo $home; ?>"></p>
</div>
<div class="col email">
<p>Work: <input class="searchable" type="text" id="email<?php echo $i; ?>" name="email<?php echo $i; ?>" value="<?php echo $email; ?>"></p>
<p>Personal: <input class="searchable" type="text" id="perEmail<?php echo $i; ?>" name="perEmail<?php echo $i; ?>" value="<?php echo $perEmail; ?>"></p>
</div>
<div class="col file">
<p class="removeFile"><input type="text" id="filename<?php echo $i; ?>" name="filename<?php echo $i; ?>" class="file" value="<?php echo $filename; ?>" readonly>
Remove: <input type="checkbox" id="removeFile<?php echo $i; ?>" name="removeFile<?php echo $i; ?>"></p>
<input type="file" id="file<?php echo $i; ?>" name="file<?php echo $i; ?>" onchange="myForm.elements['filename<?php echo $i; ?>'].value=myForm.elements['file<?php echo $i; ?>'].value;">
</div>
</div>
These rows get repeated using a javascript function which increments the name:
function addTableRow(table){
for(i=0; i<myForm.elements['entriesNum'].value; i++){
var $tr = $(table).find(".row:last").clone();
$tr.find("input,select,textarea").attr("name", function(){
var parts = this.id.match(/(\D+)(\d+)$/);
return parts[1] + ++parts[2];
}).attr("id", function(){
var parts = this.id.match(/(\D+)(\d+)$/);
return parts[1] + ++parts[2];
});
$(table).find(".row:last").after($tr);
$tr.find('.fileElements').remove();
$tr.find('input[type!="radio"], textarea').removeAttr("value");
$tr.find('input').removeAttr("checked");
$tr.find('select option:first-child').attr("selected", true);
$tr.find('input[type!="radio"]').removeAttr("disabled");
$tr.find('input[type="radio"]').attr("disabled", "disabled");
$tr.find('.error').hide();
}
}
This works perfectly until the number of rows gets higher than 111. At this point when I submit no more data gets included in the array no matter how many rows I add. I was able to deduce this by using print_r($_REQUEST);. I have edited my php.ini and set all the maxes to be absurdly high with still no change.
Whenever I've had issues with javascript created form elements not showing up in the POST, it's always had to do with the way I've structured the FORM tags.
Things to look for...
Is your FORM tag properly closed off?
Is your FORM start and close at the same level in the DOM? For example, you wouldn't want to do this...
<form method='post'>
<div>
<!--lots of stuff-->
</form>
</div>
You would instead want this...
<form method='post'>
<div>
<!--lots of stuff-->
</div>
</form>
Do you have another FORM tag that's opened and not closed before the one you're actually working with? Like this...
<form method='get'>
<!--some kind of form about something else-->
<form method='post'>
<!--the data you're currently focused on-->
</form>

Categories