Submit values from multiple textboxes as arrays - php

Basically what I want my program to do is to ask the user how many numbers they want to enter. Once the value is submitted, the program will take the value and create this amount of textboxes. Each textbox will take a number and once submitted, it should take all the numbers (excluding the initial text box) and store it into an array or something so the mean can be calculated.
I've been able to get as far as creating x amount of textboxes but cannot find a way to submit these values.
<html>
<body>
<form action="means.php" method = "get">
Enter sample size: <input type = "number" name = "size" <br>
<input type = "submit">
<?php
if ( isset($_GET["size"] ) )
{
$size = $_GET["size"];
$count = 1;
while ($count <= $size)
{
echo '<br><input type=\"text\" name=\"textbox".$count."\" />';
$count++;
}
}
?>
</form>
</html>
</body>
I assume the problem is that the textboxes created are being echoed so the name "textbox.$count." cannot be used to obtain the numbers?
Any help would be greatly appreciated. Thanks in advance!

Just use PHP's array notation for form field names:
<input type="text" name="textbox[]" />
^^---force array mode
which will produce an array in $_POST['textbox'], one element for each textbox which was submitted with the textbox[] name.
e.g:
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
produces
$_POST = array(
'textbox' => array )
0 => 1,
1 => 'foo',
2 = > 'banana'
)
)
Your problem is that you're using single-quoted strings ('), meaning that
$var = 'foo';
echo '$var' // outputs $, v, a, r
echo "$var" // outputs f, o ,o

Related

User input from 3 textboxes to be inserted into PHP-array [duplicate]

This question already has answers here:
Get all variables sent with POST?
(6 answers)
How to grab all variables in a post (PHP)
(5 answers)
How do I get the key values from $_POST?
(6 answers)
Retrieve post array values
(6 answers)
How to get an array of data from $_POST
(3 answers)
Closed 5 years ago.
I have an HTML-form with 3 inputs of type text and one input of type submit, where a name of an animal is to be inserted into each textbox. The data should then be inserted into a PHP-array.
This is my HTML-form:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal1" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal2" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal3" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
And this is my much experimental PHP-code:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1"];
$farmAnimals = $_POST["animal2"];
$farmAnimals = $_POST["animal3"];
}
// As a test, I tried to echo the saved data
echo $farmAnimals;
?>
This does not work, as the data doesn't magically turn into an array, unfortunately, which I thought it would.
I have also tried this:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1", "animal2", "animal3"];
}
echo $farmAnimals;
?>
This gives me an error message. How can I insert this data into a PHP-array?
First initialize the $farmAnimals as array, then you can push elements
if (isset ($_POST["send"])) {
$farmAnimals = array();
$farmAnimals[] = $_POST["animal1"];
$farmAnimals[] = $_POST["animal2"];
$farmAnimals[] = $_POST["animal3"];
print_r($farmAnimals);
}
Try this:
$string = "";
foreach($_POST as $value){
$string .= $value . ",";
}
Or this:
$string = implode(',', $_POST);
If you change the text field names to animal[] then you have an array of animal names when it is posted
<form action='Test.php' method='post'>
<input type='text' placeholder='Enter animal one...' name='animal[]' />
<input type='text' placeholder='Enter animal two...' name='animal[]' />
<input type='text' placeholder='Enter animal three...' name='animal[]' />
<input type='submit' value='Submit' name='send' id='send'>
</form>
You can then process that array in php easily for whatever end purpose you have - the output of which would be like this:
Array
(
[animal] => Array
(
[0] => giraffe
[1] => elephant
[2] => rhinocerous
)
[send] => Submit
)
To access these animals as an array in their own right you could do:
$animals=array_values( $_POST['animal'] );
Try naming your input fields like this:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal[0]" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal[1]" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal[2]" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
This way you be able to access those values in your PHP code like this:
if(isset($_POST["send"])) {
$farmAnimals = $_POST["animal"];
}
var_dump($farmAnimals);
// Array( [0] => Animal1, [1] => Animal2, [2] => Animal3 )
// Where Animal1,... are the values entered by the user.
// You can access them by $farmAnimals[x] where x is the desired index.
Tip: You can use empty() to check a variable for existance and if it has a "truthy" value (a value which evaluates to true). It will not throw an exception, if the variable is not defined at all. See PHP - empty() for details.
Futher reference about the superglobal $_POST array, showing this "array generating name" approach: https://secure.php.net/manual/en/reserved.variables.post.php#87650
Edit:
I just saw, that you actually overwrite your $farmAnimals variable each time. You should use the array(val1, val2, ...) with an arbitray amount of parameters to generate an numeric array.
If you prefer an associative array do this:
$myArray = array(
key1 => value1,
key2 => value2,
....
);
To append a value on an existing array at the next free index use this syntax:
// This array contains numbers 1 to 3 in fields 0 to 2
$filledArray = array(1,2,3);
$filledArray[] = "next item";
// Now the array looks like this:
// [0 => 1, 1 => 2, 2 => 3, 3 => "next item"]

Update multiple columns with multiple values in one single table

I'm making a very simple stock control system. In the page that the user will be able to do the updates, I'm listing all the contents in the table and putting everything in text fields, like the image.
So, the user should just change what he wants and when he clicks on submit, it would update every row in the table, with its respective value. But my code isn't working. I don't know how to make this kind of update and I'm sure it's wrong, because it doesn't even work. Here my form:
<form action="update_pcs.php" method="POST">
<label>Peça</label>
<label for="txtQtd" id="qtd">Qtd.</label>
<br/>
<?php foreach($rtn as $pcs){ ?>
<input type="text" name="txtNome[]" id="txtNome" value="<?=$pcs['pc_nome']?>" />
<input type="text" name="txtQtd[]" id="txtQtd" value="<?=$pcs['num']?>"/>
<input type="hidden" name="txtId[]" id="txtId" value="<?=$pcs['id']?>" />
<br />
<br />
<?php } ?>
<br />
<br />
<input type="submit" value="Enviar" name="btnEnvia" />
</form>
And my file update_pcs.php, which should do the update in the table.
<?php
include_once 'mdl.php';
$conexao = new modelDB();
$qtd = $_POST['txtQtd'];
$nom = $_POST['txtNome'];
$id = $_POST['txtId'];
/*This makes the $dados array keep in the value ['nome'] another array, the value ['qtd'] another array and ['id'] another array*/
$dados = array('nome'=>$nom,
'qtd'=>$qtd,
'id'=>$id);
foreach($dados as $dado){
/* I'm doing it that way but it isn't working */
$nomeAt = $dado['nome'];
$qtdAt = $dado['qtd'];
$id = $dado['id'];
$conexao->alteraDb("update pcs_estq set pc_nome ='{$nomeAt}', num = '{$qtdAt}' where id = '{$idAt}'");
}
My function must be right because when I change the php variables for values, it works. How could I make this right?
With sending array names in your html form, you will receive array post variables.
First change your form like below to help posting more appropriate data.
<input type="text" name="values[<?=$pcs['id']?>][Nome]" id="txtNome" value="<?=$pcs['pc_nome']?>" />
<input type="text" name="values[<?=$pcs['id']?>][Qtd]" id="txtQtd" value="<?=$pcs['num']?>"/>
<input type="hidden" name="values[<?=$pcs['id']?>][id]" id="txtId" value="<?=$pcs['id']?>" />
Actually this way you don't need to send id but i am sending for simple explanation.
Now you post, you'll receive an array like :
values => array (
1 => array (
'id'=> 1,
'Nome' => 'Some text',
'Qtd' => 1
),
2 => ....
)
Now you can get your data and insert your db.
$values = $_POST['values'];
foreach ($values as $dado) {
$nomeAt = $dado['Nome'];
$qtdAt = $dado['Qtd'];
$id = $dado['id'];
By the way, i strongly recommend using pdo, if not please make sure you validate your data before passing database query.

How to go through multiple array's and extract each value in each array using PHP?

Iam writing a program where i have a form with two fields and a 'PLUS BUTTON' upon clicking it two more fields will appear. By clicking PLUS Button again two more fields will generate and it continues as many times we click the PLUS BUTTON. Here's my program.
<form action="project_values/action_nowproject.php" method="post"enctype="multipart/form-data"><div id="item"><input type="text" name="add_qty" id="add_vender" class="ttexbox" required="required"><input type="text" name="add_name" class="ttexbox"><input onClick="addRowv(this.form);" type="button"style="cursor:pointer" class="addround" /></div></form>
in Javascript
<script type="text/javascript"> var rowNum = 0; function addRowv(frm) { rowNum ++;
var row = '<p id="rowNum'+rowNum+'"><span class="ftext">Item quantity:</span> <input type="text" name="m_name[]" value="'+frm.add_qty.value+'"><br> <span class="ftext">Item name: </span><input type="text" name="mi_name[]" value="'+frm.add_name.value+'"><br><br /> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRowsv').append(row); frm.add_qty.value = ''; frm.add_name.value = ''; } function removeRow(rnum) { jQuery('#rowNum'+rnum).remove(); } </script>
Now I have to fetch the values of extra fields appeared by clicking the plus button and send them to database.
How to fetch the values multiple array's genereated? heres my sql query insert statement.
$mp = "INSERT INTO pm_manr(name,item_nm)VALUES ('$add_qty','$item_name')";
$updata = mysql_query($mp);
How to get values in $add_qty,$item_name ? Some one pls help me.
Lets asume you have something like this:
line 1 <input name="foo[]" /> <input name="bar[]" />
line 2 <input name="foo[]" /> <input name="bar[]" />
line Y <input name="foo[]" /> <input name="bar[]" />
line Z <input name="foo[]" /> <input name="bar[]" />
You can loop trough them both by using the key from a foreach on the other values:
foreach($_POST['foo'] as $key =>$value){
echo $_POST['foo'][$key]; // the same as echo $value
echo $_POST['bar'][$key]; // the corresponding value of $_POST['bar']
// This is where you add your query
}
Use array_combine() which creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
Try this:
$arr = array_combine($_POST['m_name'],$_POST['mi_name']); // combines both arrays
foreach($arr as $key => $value){
$mp = "INSERT INTO pm_manr(name,item_nm)VALUES ('$key','$value')";
$updata = mysql_query($mp);
}

set two values for an input name attribute

i have a check box list that some limited check boxes can be selected. for this i set the name attr of all them "answer" to work with the js function properly(i got the function from some where).
<?php
else if($result['type'] == "multipleChoice"){
echo'
<div><input type="checkbox" name="answer ans1" value="'.$res['probAns1'].'"/><input type="text" class="prob-ans" name="prob-ans1" value="'.$res['probAns1'].'"/><lable>:گزینه 1</lable></div>
<div><input type="checkbox" name="answer ans2" value="'.$res['probAns2'].'"/><input type="text" class="prob-ans" name="prob-ans2" value="'.$res['probAns2'].'"/><lable>:گزینه 2</lable></div>
<div><input type="checkbox" name="answer ans3" value="'.$res['probAns3'].'"/><input type="text" class="prob-ans" name="prob-ans3" value="'.$res['probAns3'].'"/><lable>:گزینه 3</lable></div>
<div><input type="checkbox" name="answer ans4" value="'.$res['probAns4'].'"/><input type="text" class="prob-ans" name="prob-ans4" value="'.$res['probAns4'].'"/><lable>:گزینه 4</lable></div>
';
?>
first is it correct to set two value for name attr. i did it but didnt work. like it isnt acceptable the second value.
if not how can i specify them if i have just name="answer"? i want to set some values in php if one of these check boxes is set.
<?php
if($result['type'] == "multipleChoice"){
$question->probAns1 = mysql_real_escape_string($_POST['prob-ans1']);
$question->probAns2 = mysql_real_escape_string($_POST['prob-ans2']);
$question->probAns3 = mysql_real_escape_string($_POST['prob-ans3']);
$question->probAns4 = mysql_real_escape_string($_POST['prob-ans4']);
if(isset($_POST['ans1'])){
$question->answer1 = $_POST['prob-ans1'];
}
}
?>
No, you can't have two names like you did. Following however is possible:
<input type="checkbox" name="answer[]" value="abc" />
<input type="checkbox" name="answer[]" value="def" />
Your $_POST will look like following (if both are checked):
array(
'answer' => array(
0 => 'abc',
1 => 'def'
)
)
You can also specify the array-keys, thus name="answer[answ1]" value="abc" will give you $_POST['answer']['answ1'] == 'abc'
Here is link of what you need to do.
In one sentence, you need to use arrays of html elements.

PHP form processing with variableform inputs

Got a form that has the option to add many inputs for ordering pictures via picture number.
In theory a customer could order 1 picture or 100, how would I go about the PHP.
As coding up to 100 $_POST[] for each possible field seems crazy as each of the added fields as it's own unique NAME attr using jQuery.
Anyone got any bright ideas?
Using field names that end in square brackets will cause PHP to create the entries as an array:
<input name="foo[]" value="foo" />
<input name="foo[]" value="bar" />
<input name="foo[]" value="moo" />
<input name="foo[]" value="cow" />
will produce the following: $_REQUEST['foo'] (or $_POST['foo']/$_GET['foo']) is an array like this:
array(
0 => 'foo',
1 => 'bar',
2 => 'moo',
3 => 'cow'
);
You could try something like
for ($i=0;$i<100;$i++){
if (isset($_POST['picture'.$i])){
// Do something
} else {
break;
}
}
You can do something like this
<input type="checkbox" value="picnumber" name="pictures[]" />
<?php
$pics = $_POST['pictures']; // here you will get an array of values of the selected images
?>

Categories