PHP form processing with variableform inputs - php

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
?>

Related

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.

What changes need to make to the HTML input fields in order to create desired array in PHP?

I've designed one HTML form as follows :
<form action="sample_test.php" method="post">
<input type="text" name="fileName" value="8.png" id="fileName[]">
<input type="text" name="fileLink" value="https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd" id="fileLink[]">
<input type="text" name="fileName" value="2_OnClick_OK.jpg" id="fileName[]">
<input type="text" name="fileLink" value="https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ" id="fileLink[]">
<input type="submit" name="Submit" value="Submit File">
</form>
Then the code in sample_test.php is as follows :
<?php
print_r($_POST); die;
?>
The output I got is as follows :
Array ( [fileName] => 2_OnClick_OK.jpg [fileLink] => https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ [Submit] => Submit File )
But this is not the desired output. I want the desired output array to be printed in following manner:
Array
(
[8.png] => Array
(
[0] => https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd
)
[2_OnClick_OK.jpg]
(
[0] => https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ
)
)
For now I've just demonstrated with two elements only but in real situations hundreds of such elements could present on the form.
So what changes do I need to make in my HTML as well as PHP code? Please help me.
Thanks in advance.
What you ask is impossible by just modifying the HTML code, because you would like a value (of fileName) to become an index in the array you get. That's impossible, the index will always be the name of the input.
However, if you have a look here : POSTing Form Fields with same Name Attribute , you will be able to get arrays of fileName and fileLink, and I'm pretty sure you can do something from there.
A few things wrong, but you are close. Make the name field an array instead of the id - plus your ids need to be unique.
<input type="text" name="fileName[]" value="8.png" id="fileName1">
<input type="text" name="fileLink[]" value="https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd" id="fileLink1">
<input type="text" name="fileName[]" value="2_OnClick_OK.jpg" id="fileName2">
<input type="text" name="fileLink[]" value="https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ" id="fileLink2">
Not tested, but should do the trick.

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.

zend : populating a checkbox array with $form->populate(); from controller

We have a zend form with text input fields and array of checkboxes, as shown below -
<input class="checkbox_Category" type="checkbox" name="tag[]" value="19"> somename1 <br/>
<input class="checkbox_Category" type="checkbox" name="tag[]" value="20"> somename2 <br/>
<input class="checkbox_Category" type="checkbox" name="tag[]" value="21"> somename3 <br/>
and using a
$formObject->populate($formDataArray);
in the controller to populate data in the whole form. All the text input fields seem to populate fine, but the checkboxes don't. Int the $formDataArray, the data for the checkboxes is in the format
[tag] => Array ( [0] => 20 [1] => 19 )
Along with the other form data like - [firstName] => 'somename' etc.
I am not able to figure out the format of the data the form is expecting, in order to get populated with populate();
hi might be problem with the name you have given as array please change like below
<input class="checkbox_Category" type="checkbox" name="tag" value="19"> somename1 <br/>
<input class="checkbox_Category" type="checkbox" name="tag" value="20"> somename2 <br/>
<input class="checkbox_Category" type="checkbox" name="tag" value="21"> somename3 <br/>
Please let me know if i can help you further
Without actually seeing your Zend_Form code, this is very difficult. However, most often, I've seen people mistake the 'checkbox' element with the 'multiCheckbox' element in Zend Framework. I know - it's a bit confusing - but checkbox is a single checkbox with an on/off value. MultiCheckbox handles multiple values - and I think it's what you are trying to accomplish. Let me show you a quick form that will work and generate your HTML above.
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$multiOptions = array(
19 => 'somename1',
20 => 'somename2',
21 => 'somename3'
);
$this->addElement('multiCheckbox', 'tag', array(
'multiOptions'=>$multiOptions
));
$this->addElement('submit', 'submitbutton');
}
}
Now, if you use something like...
$form->populate($this->getRequest()->getPost());
in your controller, it will populate as expected.
Hope this helps!

3 checkboxes with same name and same same numeric value

Given this code:
<input type="checkbox" id="Coke" name="Price" value="70" />
<input type="checkbox" id="Fanta" name="Price" value="70" />
<input type="checkbox" id="Sprite" name="Price" value="70" />
I would like to know how, if my user selects Fanta checkbox, I want my php variable $type="Fanta" but I need form checkbox VALUES to stay NUMERIC for total price calculation.
It's not clear what exactly you're asking, but I believe you basically want 2 fields, one that defines the price and one that defines the selected type.
In that case, your best bet would be to store the prices server-side (That way people can't modify them too, which is good!). If you do this, your checkboxes will look like this:
<input type="checkbox" id="Coke" name="type[]" value="Coke" />
<input type="checkbox" id="Fanta" name="type[]" value="Fanta" />
<input type="checkbox" id="Sprite" name="type[]" value="Sprite" />
Your backend code would look like this:
$prices = array(
'Coke' => 70,
'Fanta' => 70,
'Sprite' => 70
);
$types = $_POST['type'];
$total = 0;
foreach($types as $key => $type) {
if (!isset($prices[$type]))
continue;
$total += $prices[$type];
}
// Use $total as your total price for whatever calculation
echo $total;
As per your comment, if you still want these prices client side for calculations, you can use json_encode to output it into a script tag and use the prices directly. It's basically going to turn the server-side prices array into a client-side array of prices.
<script type="text/javascript">
var prices = <?= json_encode($prices) ?>;
// Now you can use prices['Coke'] etc, based off the value of the selected checkbox.
</script>
I would like to know how, if my user selects Fanta checkbox,
Then name you field fanta:
<input type="checkbox" id="Fanta" name="fanta" value="70" />
Once you have done that you can get the values using either the $_POST or the $_GET superglobal (depending on your form method):
if (isset($_POST['fanta'])) {
echo $_POST['fanta'];
}
However you should never ever ever rely on the prices coming from the clientside!
but I need form checkbox VALUES to stay NUMERIC for total price calculation.
That is not going to happen because in HTTP values are being send as strings. Luckily PHP does automatic type juggling for you so you will still be able to do calculations with the string values.
http://codepad.viper-7.com/GOhHdz
In some situations you want to make it a integer value explicitly. In that case you can use type casting:
var_dump((int) '18');
http://codepad.viper-7.com/kJlGoS
When you post a form, anyway you will get 70 as value.
echo $_POST['Price'];
gives 70
<input type="checkbox" value="Coke" name="Price" rel=70 />
<input type="checkbox" value="Fanta" name="Price" rel="70" />
<input type="checkbox" value="Sprite" name="Price" rel="70" />
use javascript to get rel attribute value for selected checkbox for total price

Categories