I've got an array containing animals. I print out the array using a foreach loop. I would like to update the value of a specific key, without changing any of the other values which have different keys. I have an update input box next to each key for the value to go in it. When I type a value for key 0, for example, all the other key values change too, not just 0
So my output is something like this:
The value of $_SESSION['0'] is 'cat' // i want to change cat to something else
The value of $_SESSION['1'] is 'dog' // dog to something else
The value of $_SESSION['2'] is 'mouse' /mouse to something else
this is my code and it so frustrating becuase I have added $key to each input in the foreach loop...
**code
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');
// put the array in a session variable
$_SESSION['animals']=$my_array;
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
// getting the updated value from input box
if (isset($_POST["submit"])) {
$aaa = $_POST['aaa'];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key] = $aaa;
}
?>
<form method="post" action="testthis.php">
<input type="text" name="aaa" value="<?php echo $value ; ?>" size="2" />
<input type="submit" value="Add to cart" name="submit"/></div>
</form>
<?php
}
echo"<br/>---------------------------------------------------------<br/>";
//echoing out the results again for the updated version
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>
Try following code.
Edits:
1) move isset($_POST["submit"]) outside foreach loop so that it will not update all the sessions.
2) take hidden input with the value of key to be updated so that we can concentrate only on one key which is to be updated.
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
$aaa = $_POST['aaa'];
$key_var = $_POST['ke'];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
// getting the updated value from input box
?>
<form method="post" action="">
<input type="text" name="aaa" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke" value="<?php echo $key; ?>">
<input type="submit" value="Add to cart" name="submit"/></div>
</form>
<?php
}
echo"<br/>---------------------------------------------------------<br/>";
//echoing out the results again for the updated version
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>
Related
I have a problem with <form> in php .
i have uncertain number of fields (inputs) . it may be 1 or 100 input field .
Is there any function or class to get uncertain number of fields ?
Try that :
echo '<form>';
foreach ($data as $value) {
echo '<input name="field[]" value="',$value,'">';
}
echo '<input type="submit"></form>';
If you send that form, $_POST['field'] will be an indexed array in which every entry will correspond to one of the inputs.
$_POST would contain all the fields from the form on submit
print_r($_POST) will display them in an array for you
You can use an array name for the input fields in your form. For example, you can make an array of title fields by adding [] after the name:
<input type="text" name="title[]" />
<input type="text" name="title[]" />
<input type="text" name="title[]" />
Now in your PHP code, this value will be an array containing an amount of values equal to the number of fields with this name. The following code would print all titles on separate lines:
foreach ($_REQUEST['title'] as $value)
echo $value . "\n";
Just count the $_POST or $_GET what you use.
<?php
if(isset($_POST['submit'])){
echo "The total number of input fields is";
echo count($_POST); // include submit also
}
?>
I have an array stored inside a session. I have echoed out each key and value using a foreach loop. Next to each key there is an input box for updating the value for that specific key.
The problem is that, each input box has its own submit button for updating the value. I want to make it only one submit that updates all input boxes.
I tried placing the submit button and the outside of the loop. But that only updates the last value in the loop and not any other one.
I tried having it even outside the php and rewriting it as html, but it still didnt work for some reason.
THANKS in advance!
MY CODE!
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse');
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
$aaa = $_POST['aaa'];
$key_var = $_POST['ke'];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of key ' .$key. ' is '."'".$value."'".' <br />';
echo "update the value of key " .$key. " in the input box bellow";
// getting the updated value from input box
?>
<form method="post" action="">
<input type="text" name="aaa" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke" value="<?php echo $key; ?>">
<input type="submit" value="Update value of key" name="submit"/></div>
</form>
<?php
}
?>
UPDATE
So I used Vijaya Sankar N's code and Audite Marlow' code and they both work perfectly.
Updated code by Audite Marlow
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse');
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
for ($i = 0; $i < count($_POST['aaa']); $i++) {
$aaa = $_POST['aaa'][$i];
$key_var = $_POST['ke'][$i];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
}
?>
<form method="post" action="">
<?php
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of key ' .$key. ' is '."'".$value."'".' <br />';
echo "update the value of key " .$key. " in the input box bellow";
// getting the updated value from input box
?>
<input type="text" name="aaa[]" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke[]" value="<?php echo $key; ?>">
<?php
}
?>
<input type="submit" value="Update value of key" name="submit"/>
</form>
Put the form around your foreach loop. Put the submit button outside of your foreach loop, inside your form. Inside the foreach loop, make the names of your inputs an array, like so:
<form method="post" action="">
<?php
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of key ' .$key. ' is '."'".$value."'".' <br />';
echo "update the value of key " .$key. " in the input box bellow";
// getting the updated value from input box
?>
<input type="text" name="aaa[]" value="<?php echo $value ; ?>" size="2" />
<!-- take a hidden input with value of key -->
<input type="hidden" name="ke[]" value="<?php echo $key; ?>">
<?php
}
?>
<input type="submit" value="Update value of key" name="submit"/></div>
</form>
Now, in your isset($_POST['submit']) { ... }, you want to loop through your input arrays like so:
if (isset($_POST["submit"]))
{
for ($i = 0; $i < count($_POST['aaa']); $i++) {
$aaa = $_POST['aaa'][$i];
$key_var = $_POST['ke'][$i];
// setting the session spesific session array value different for each key
$_SESSION['animals'][$key_var] = $aaa;
}
}
This way, you'll update all $_SESSION['animals'] keys for every input.
The problem isn't the position of the buttons, but the form and /form tags
When you click a button that is insiede a form /form block, the browser send all the data INSIDE the block.
If you want to update ALL the elements with one button, you have to open the form tag before the "foreach" block and close the /form tag outside the foreach block
Just put everything in one form with one submit button. Than you need to make the input name unique, cause else only the last value will be submitted. I did this by creating an 'animal' input array. In your PHP you can just simply loop through the POST data.
Try this:
<?php
// begin the session
session_start();
// create an array
$my_array=array('cat', 'dog', 'mouse');
// put the array in a session variable
if(!isset($_SESSION['animals']))
$_SESSION['animals']=$my_array;
// move submit code outside of foreach loop
if (isset($_POST["submit"]))
{
//Your new PHP to update all values
if(isset($_POST['animal']) && count($_POST['animal']) > 0)
{
foreach($_POST['animal'] as $key => $value)
{
$_SESSION['animals'][$key] = $value;
}
}
}
?>
<form method="post" action="">
<?php
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo 'The value of key ' .$key. ' is '."'".$value."'".' <br />';
echo "update the value of key " .$key. " in the input box bellow";
// getting the updated value from input box
?>
<input type="text" name="animal[<?= $key ?>]" value="<?= $value ?>" size="2" />
<?php
}
?>
<input type="submit" value="Update all values" name="submit"/></div>
</form>
Move the form and button outside the foreach and generate text fields with the key as identifier.
<form method="post" action="">
<?php
foreach($_SESSION['animals'] as $key=>$value)
{
echo 'The value of key ' .$key. ' is '."'".$value."'";
echo "update the value of key " .$key. " in the input box bellow <br />";
echo "<input type='text' name='$key' value='$value' size='2' /> <br />";
}
?>
<input type="submit" value="Update value of key" name="submit"/></div>
</form>
and your PHP submit code will be as simple as:
foreach($_POST as $key=>$value){
$_SESSION['animals'][$key] = $value;
}
I input values from HTML form as array like this:
<form method = "post" action = "akf.php">
Enter Values in Array $a:<br><br>
<input type="text" name="a[one]" />
<input type="text" name="a[two]" />
<input type="text" name="a[three]" />
<input type="text" name="a[four]" />
<input type="text" name="a[five]" />
<br><br><input type="submit" value="Find"><br><br>
</form>
Now I get those input from PHP from the HTML form and display it like this:
$a=$_POST['a'];
print_r($a);
Now without giving any input in the form (ie., An Empty form) if I submit the form,
It should return the message "No Values entered in the Array ".
Note: I want the PHP to return the above message only after I submit the form.
Functions and Syntax's I used to achieve the output:
if (empty($a))
{
echo 'No Values entered in the Array';
}
else
{
echo 'Array';
}
This doesn't work because: I only returns the message "No Values entered in the Array" when the page is loaded newly, when I click the submit button, PHP takes some value as input and returns the message array.
$sum = array_sum($a);
if($sum==0)
{
echo " No Values entered in the Array ";
}
else
{
echo 'Array';
}
This syntax works only when all the inputs are numerical (numbers of any type) . If I enter strings in array through html forms and SUBMIT, it still prints "No Values entered in the Array"
since array_sum($a); doesn't count strings.
It returns Array because even if you don't enter anything empty strings will be submitted. So if you enter nothing your array will be full of empty strings.
To check if there are only empty strings do:
if(!array_filter($a)) {
echo 'No Values entered in the Array';
}
else {
echo 'Array';
}
array_filter will compare all elements to false and if they are false they will be removed. So if all elements in the array are an empty string the returned array will be empty and therefore validated to false.
See also: Checking if all the array items are empty PHP
you form is:
<form method = "post" action = "akf.php">
Enter Values in Array $a:<br><br>
<input type="text" name="a[]" />
<input type="text" name="a[]" />
<input type="text" name="a[]" />
<input type="text" name="a[]" />
<input type="text" name="a[]" />
<br><br><input type="submit" value="Find"><br><br>
</form>
no need to add any key.
php part:
$values = array_filter($a);
if (!empty($values)) {
echo 'no value';
}else{
echo 'array';
}
In your case you can try something like:
$somethinginarray = false;
foreach($a as $value) {
if(!empty($value)) { // trim this one or put more efficient validation
$somethinginarray = true;
}
}
if($somethinginarray) echo 'Array';
else echo " No Values entered in the Array ";
I have a form which builds the form items from a foreach loop and puts a checkbox by each item:
<form action="nextStep.php">
<?php
foreach ($children[0] as $myPage) {
$menuname = $info[$myPage]['label'];
echo '<input type="checkbox" id="'.$menuname.'" name="reveal_menu" value="no" unchecked><label for="'.$menuname.'">'.$menuname.'</label><br>';
}
?>
<br>
<input type="submit" value="Submit">
</form>
As you can see, I start with each item unchecked. What I would like to know is how I should build the nextStep.php script to create individual php variables that I can echo on the nextStep.php page after the user clicks the submit button?
You must identify that this input is an array of values, by appending [] on the name:
echo '<input ... name="reveal_menu[]" ...>';
In nextStep.php:
foreach($_POST['reveal_menu'] as $checkbox)
echo $checkbox;
EDIT to answer OP comment:
You would need to create an array to handle these values. But $_POST['reveal_menu'] itself is an array. So can access $_POST['reveal_menu'][0], for example.
Keep in mind that $_POST['reveal_menu'] is an array with checked values ONLY . The index 0 doesn't point for the first checkbox of your form, but for the first checkbox checked from your form.
Each item needs to have a unique value, probably the menuname, so you can tell which ones are checked, and the name needs to have [] operator appended to the end.
<form action="nextStep.php">
<?php
foreach ($children[0] as $myPage) {
$menuname = $info[$myPage]['label'];
echo '<input type="checkbox" id="'.$menuname.'" name="reveal_menu[]" value="$menuname" unchecked><label for="'.$menuname.'">'.$menuname.'</label><br>';
}
?>
<br>
<input type="submit" value="Submit">
</form>
When you loop through, you'll get an array of values.
<?php
foreach($_POST['menuname'] as $v)
{
echo($v . 'Was checked.');
}
?>
<?php
// code that connects to database
?>
<table>
<form method="get" action="processorder.php">
<?php
while (list($pizzaId, $pizzaName, $pizzaNumber, $pizzaPrice) = mysql_fetch_row($resultaat))
{
echo "<tr>
<td>".$pizzaName."</td>
<td>".$pizzaNumber."</td>
<td>".$pizzaPrice."</td>
<td> <input type='text' name='$pizzaId' value='$qty' size='3' /></td>
</tr>";
}
mysql_close($db);
?>
<input type="submit" value="Order now" />
I would like to display the pizzas of where there is a value in the input element.
the processorder.php file would look like:
my url shows the pizzaId's with the values after the '='. So I figured I have an associative array on my hands.
I thought I'd put a foreach loop in my processorder.php going like
foreach ($_GET['pizzaId'] as $pizza => $qty)
{
echo $pizza." ".$qty."<br />";
}
Yet, when I use the foreach loop, the error in my browser says that the argument of my foreach loop is invalid because $_GET['pizzaId'] isn't an array to begin with (I checked with is_array).
So how do I get access to those values in my value attribute of the input element?
Your $pizzaId is an integer.
I would change the name of the input elements to name="pizzas[$pizzaId]", and then you could access it through PHP like this:
foreach ($_GET["pizzas"] as $pizzaId => $pizzaQty) {
echo "$pizzaId $pizzaQty<br />";
}
with this method, instead of just plain name="pizzas[]", you also retain the association with the actual pizzaId.
If you need to put an array into $_GET then your url should look like:
//site/page?pizzaID[]=123&pizzaID[]=124
You can achive this with similar usage of name of input field
<input name="pizzaID[]" />
<input name="pizzaID[]" />