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.
Related
I'm making a todo list and I've got everything working except for this one thing. I need to loop over inputs that's been submitted via a form, these inputs have the same name so what I've done is storing them as an array. Now I need to loop over them so I can send them into the database one by one. Here's what I tried:
if (isset($_POST['submit'])) {
$labelValues = $_POST['labelValue[]'];
$i = 0;
while($i < sizeof($labelValues)) {
$stmt = $db->prepare("INSERT INTO tenta_table (text) VALUES (:text)");
$stmt->bindParam(':text', $labelValues[$i]);
$stmt->execute();
$i++;
}
}
HTML, the inputs are marked with red:
But it doesn't seem to work, it's not giving me any errors so I have nothing to go on. Where am I going wrong here?
Your $_POST['labelValue'] will already be an array if you have named your inputs correctly, something like <input type="text" name="labelValue[]" /> would create and array called labelValue in your POST.
From there you should be able to use your current code with one minor change
if (isset($_POST['submit'])) {
$labelValues = $_POST['labelValue'];
$i = 0;
while($i < sizeof($labelValues)) {
$stmt = $db->prepare("INSERT INTO tenta_table (text) VALUES (:text)");
$stmt->bindParam(':text', $labelValues[$i]);
$stmt->execute();
$i++;
}
}
Above I have change $labelValues to equal $_POST['lableValue'] rather than $_POST['labelValue[]']
In your case only the last input element will be available.
If you want multiple inputs with the same name use name="foo[]" for the input name attribute. $_POST will then contain an array for foo with all values from the input elements.
<form method="post">
<input name="a[]" value="foo"/>
<input name="a[]" value="bar"/>
<input name="a[]" value="baz"/>
<input type="submit" />
</form>
The reason why $_POST will only contain the last value if you don't use [] is because PHP will basically just explode and foreach over the raw query string to populate $_POST. When it encounters a name/value pair that already exists, it will overwrite the previous one.
However, you can still access the raw query string like this:
$rawQueryString = file_get_contents('php://input'))
Assuming you have a form like this:
<form method="post">
<input type="hidden" name="a" value="foo"/>
<input type="hidden" name="a" value="bar"/>
<input type="hidden" name="a" value="baz"/>
<input type="submit" />
</form>
the $rawQueryString will then contain a=foo&a=bar&a=baz.
You can then use your own logic to parse this into an array. A naive approach would be
$post = array();
foreach (explode('&', file_get_contents('php://input')) as $keyValuePair) {
list($key, $value) = explode('=', $keyValuePair);
$post[$key][] = $value;
}
which would then give you an array of arrays for each name in the query string.
or the best and simple approach for this
<form method="post">
<input name="a[0]" value="foo"/>
<input name="a[1]" value="bar"/>
<input name="a[2]" value="baz"/>
<input type="submit" />
</form>
You should replace
$labelValues = $_POST['labelValue[]'];
By
$labelValues = $_POST['labelValue'];
Not Sure, but as far as i remember it should be $labelValues = $_POST['labelValue']. I think your $labelValues is null and you don't even enter your loop. You should do a var_dump( $_POST ) to verify what you're working with.
I am trying to create a form that gets a user directions to a pre-defined location from the location that they entered. I am using Bing Maps 'create a custom url map' to achieve this.
Based on msdn (http://msdn.microsoft.com/en-us/library/dn217138.aspx) I know I need the form to pass a single value such as the following: rtp=adr.'addressfromuser'~adr.'predefined address' . I just don't know how to merge the form values (or insert adr. in front of the user input). I have been unable to find a way to do this so any help is appreciated.
my code for my form is below:
<form action="http://bing.com/maps/default.aspx" method="get" target="_blank">
<label for="rtp">From:</label>
<input class ="input" type="text" name="rtp" value="adr." /> <!--user input-->
<input type="hidden" name="rtp" value="~adr.Mission,TX" />
<!--predetermined destination-->
<input class="btn btn-primary" type="submit" type="submit" value="Get directions" />
</form>
Ding this gets a result that is close to what I want but not quite there (would like to hide the initial "adr." and not generate a "rtp=" before the 2nd rtp being passed. Note: if I comment out the user inputs I successfully get a map with the final destination as point b, but no point a defined
If what I'm trying to do is possible help is appreciated!
You would need to array your ftp input:
EDIT: YOU NEED TO REMOVE adr. in the value="adr." on both rtp inputs!
<form action="http://bing.com/maps/default.aspx" method="get" target="_blank">
<label for="rtp">From:</label>
<input class ="input" type="text" name="rtp[]" value="" /> <!--user input-->
<input type="hidden" name="rtp[]" value="Mission,TX" />
<!--predetermined destination-->
<input class="btn btn-primary" type="submit" value="Get directions" />
</form>
Then, when you process the form, you would implode() that rtp[] array like so:
<?php
/* $_GET['rtp'] will look like this before implosion:
array(
0 => FromCity,UT
1 => ToCity,CA
)
*/
// You need to pre-append the adr. value to both strings by looping array
foreach($_GET['rtp'] as $value) {
$_rtp[] = "adr.'".$value."'";
}
/* Now $_rtp looks like this:
array(
0 => adr.'FromCity,UT'
1 => adr.'ToCity,UT'
)
*/
// Now implode this new array with "~"
// You could assign a new variable to the implode, but if you wanted to,
// you could override the same $_GET['rtp'] variable with it's imploded self.
$_GET['rtp'] = implode("~",$_rtp);
// Now the $_GET['ftp'] = adr.'FromCity,UT'~adr.'ToCity,UT'
?>
use javascript/jquery
$('form').submit(function(){
//do your actions here
$('input[name=rtp]').value()
return false; // prevents submit by default action.
});
i have a kohana application, and i have a form with several checkboxes, and the user is supposed to check his preferences there in the form. so i have a relation 1:n between the user table and the preferences table. my problem is that i want to save those preferences, selected in the form, and i don;t know how.
i have the form:
<form id="address" method="POST" action="<?= Route::url('Save user preferences' , array('user_id' => $user));?>">
<? foreach ($prefered_products as $pp): ?>
<input type="checkbox" name="user_preferences_preference[]" value="<?= $pp ?>" /><?= $pp->product; ?><br />
<? endforeach; ?>
<button type="submit">Salveaza preferintele tale</button>
</form>
and i save the data:
foreach ($_POST['user_preferences_preference'] as $up) {
$user_preferences->prefered = $up;
$user_preferences->user = $this->user;
$user_preferences->save();
}
$this->view->message = __('Thank you for your feedback!');
but seems like the way i parse the preferences is not correct, i am getting: ErrorException [ Warning ]: Invalid argument supplied for foreach()
any idea about how am i supposed to get the multiple $_post preferences?
thank you!
I have a slightly different way of doing this.
When I create a checkbox I also create an identical hidden field set to zero
<input type="hidden" name="my_check" value="0" />
<input type="checkbox" name="my_check" value="$value" />
The checkbox, if ticked, will override the hidden value. This way when you send the form you end up with $_POST['checkbox]=1 or 0, but it always exists in the $_POST.
The nice thing about this method is you can extend the Form::checkbox helper so that it's always present and you don't have to worry about it for every form / controller.
p.s. in you above example you would probably want to do it like this:
<input type="hidden" name="user_preferences_preference[$pp->id]" value="0" />
<input type="checkbox" name="user_preferences_preference[$pp->id]" value="<?= $pp ?>" />
<?= $pp->product; ?><br />
Or use a $key value instead of $pp->id.
The problem is that a checkbox will only post data when set. You should reverse check the values. Ie;
Fetch all preference (id's) from the database
Check if a value is found in the $_POST var
If not, update to false (or 0 or whatever) in db, if set, read out the value.
I am trying to add commenting like StackOverflow and Facebook uses to a site I'm building. Basically, each parent post will have its own child comments. I plan to implement the front-end with jQuery Ajax but I'm struggling with how to best tackle the PHP back-end.
Since having the same name and ID for each form field would cause validation errors (and then some, probably), I added the parent post's ID to each form field. Fields that will be passed are commentID, commentBody, commentAuthor - with the ID added they will be commentTitle-12, etc.
Since the $_POST array_key will be different each time a new post is processed, I need to trim off the -12 (or whatever the ID may be) from the $_POST key, leaving just commentTitle, commentBody, etc. and its associated value.
Example
$_POST['commentTitle-12']; //how it would be received after submission
$_POST['commentTitle']; //this is what I am aiming for
Many thanks
SOLUTION
Thanks to CFreak-
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$title = $_POST['title'][0];
$body = $_POST['body'][0];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[]"/>
<input type="text" name="body[]"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
Update 2
Oops, kind of forgot the whole point of it - unique names (although it's been established that 1) this isn't really necessary and 2) probably better, for this application, to do this using jQuery instead)
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$id = $_POST['id'];
$title = $_POST['title'][$id];
$body = $_POST['body'][$id];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[<?php echo $row['id'];?>]"/>
<input type="text" name="body[<?php echo $row['id'];?>]"/>
<input type="hidden" name="id" value="<?php echo $row['id']; //the ID?>"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
PHP has a little trick to get arrays or even multi-dimensional arrays out of an HTML form. In the HTML name your field like this:
<input type="text" name="commentTitle[12]" value="(whatever default value)" />
(you can use variables or whatever to put in the "12" if that's what you're doing, the key is the [ ] brackets.
Then in PHP you'll get:
$_POST['commentTitle'][12]
You could then just loop through the comments and grabbing each by the index ID.
You can also just leave it as empty square brackets in the HTML:
<input type="text" name="commentTitle[]" value="(whatever default value)" />
That will just make it an indexed array starting at 0, if you don't care what the actual ID value is.
Hope that helps.
You just have to iterate through $_POST and search for matching keys:
function extract_vars_from_post($arr) {
$result = array();
foreach ($arr as $key => $val) {
// $key looks like asdasd-12
if (preg_match('/([a-z]+)-\d+/', $key, $match)) {
$result[$match[1]] = $val;
} else {
$result[$key] = $val;
}
}
return $result;
}
Didn't test the code, though
Let me explain.
Normally when hidden fields are passed from a form to the page specified in the action of the form, those hidden fields can be accessed on the processing page like so:
The Form:
<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="loginTime" value="1:23PM" />
<input type="hidden" name="userIp" value="173.23.22.5" />
<input type="submit" name="submit" value="Submit" />
</form>
Processing Page (process.php):
<?php
if isset($_POST['submit']) {
echo $_POST['username'];
echo $_POST['loginTime'];
echo $_POST['userIp'];
}
?>
You see how I had to call the two hidden fields by name and individually. Is there any way I can call all hidden fields that are passed to a page from a form all at once despite what the field names of those are or how many there are?
In other words how do I make PHP do this:
// echo the contents of all hidden
fields here (if there were any)
EDIT
Additional info:
The form is designed in such a way (not the one above of course) that field names will be of the following sort:
product_name_1
product_quantity_1
product_price_1
product_name_2
product_quantity_2
product_price_2
and so incremented so on...
Depending on the user action there can be 3 hidden fields or thousands, there are no limits.
Make an array of valid hidden field names, then iterate through $_POST and if the $_POST field name is in the array of valid field names, echo them.
$valid = array('first_name', 'last_name');
foreach ( $_POST as $key => $value ) {
if ( in_array( $key, $valid ) ) {
echo $_POST[$key];
}
}
PHP does not care whether the field was hidden or not, HTTP doesn't tell PHP how it appeared on the website.
The closest thing I would come up with was saving all names of the hidden fields inside an array and echoing them all in a loop.
You can try the following:
<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="group_hidden[loginTime]" value="1:23PM" />
<input type="hidden" name="group_hidden[userIp]" value="173.23.22.5" />
<input type="submit" name="submit" value="Submit" />
</form>
And then print it:
echo htmlspecialchars(print_r($_POST, true));
This might give you a clue about how to solve this.
there's no way to tell the type of the input built-in, so instead you'll need to come up with a way to identify the ones you want yourself. This can be done either by coming up with a special naming scheme, or by storing a list of the names of the hidden fields in another field. I'd recommend the former option, since you don't have the risk of losing data integrity somehow. Look at using array_filter to parse through the array to get the specially-named fields out.
Maybe, assuming that your hidden fields will be in sequence (i.e. 1,2,3 and not 1,2,4) following all of the end users' actions (adding and taking away fields), you could try something along the lines of
$i = 1;
while(isset($_POST["product_name_$i"]))
{
echo $_POST["product_name_$i"];
echo $_POST["product_price_$i"];
$i++;
}
Or something along those lines?