I would like to pass an array from a form by changing its values (inputs).
the user can change the values of the inputs,
how could retrieve the array changed?
for example...
<?php $vector = array("product1" => 150, "product2" => 120); ?>
<table>
<form action="page2.php" method="get">
<?php foreach ($vector as $key => $value) {
echo "<tr><td>Product: $name</td><td><input type='text' name='$key'
value='$value'/>
</td>";
}
<tr>
<td><input type="submit" name="process" value="Submit" /></td>
</tr>
</form>
</table>
?>
// on the other page...page2.php
if (isset($_GET['process'])){
$foo = $_GET[$vector]; // the array i want
echo var_dump($foo);
}
HTTP, by design, allows arrays through POST/GET. Simply have the related items with the same name and ending with two opposing square brackets, like so:
<input type="text" name="data[]" value"First"/>
<input type="text" name="data[]" value"Second"/>
And on the server...
print_r($_REQUEST['data']);
Prints...
Array
(
[0] => First
[1] => Second
)
Pretty convenient, hmm?
Parameters are passed as an array form. So you have to parse the requested variables
Here is the revised version of your code.
<?php $vector = array("product1" => 150, "product2" => 120); ?>
<table>
<form action="page2.php" method="get">
<?php foreach ($vector as $key => $value) {
echo "<tr><td>Product: $name</td><td><input type='text' name='$key'
value='$value'/>
</td>";
}
<tr>
<td><input type="submit" name="process" value="Submit" /></td>
</tr>
</form>
</table>
?>
// on the other page...page2.php
if (isset($_GET['process'])){
unset($_GET['process']);
$foo = $_GET ;
echo var_dump($foo);
}
Try to just make it
$foo = $_GET ;
If you don't want the 'process' to be in the array, first call
unset($_GET['process']);
Related
Okay #AlexioVay this is I what have on the first page form.php
<?php
$fruits = [
'Orange' => 10,
'Banana' => 12,
'Apple' => 15,
'Lemon' => 8
];
?>
<form method="post" action="next.php">
<?php
// With this syntax we say "$key equals $value" ($fruit => $price)
foreach($fruits as $fruit => $price) {
// We use '. $variable .' to merge our variables into HTML
// Since we are in a loop here all the items from the array will be displayed:
echo '<input type="checkbox" name="'.$fruit.'" />
$'.$price.' - '.$fruit;
}
?>
<button type="submit">Submit</button>
</form>
and on my second page next.php,
<table style="width:100%">
<tr>
<?php
foreach($_POST as $fruit) {
echo "<td>".$fruit."</td>";
}
?>
</tr>
</table>
So when i select options on the first page then press submit the data am getting on the next page is just the word "on"
here is example, i dont know if you can open this link https://test.ftgclothing.net then you can see what am talking about
The best way would be a foreach loop that displays what items have been selected in the $_POST variable:
<table style="width:100%">
<tr>
<?php
foreach($_POST as $fruit) {
echo "<td>".$fruit."</td>";
}
?>
</tr>
</table>
Also you should use checkboxes in the file before, not radio buttons, because with radio buttons you can only select one item of a group of items:
<form method="post" action="next.php">
<input type="checkbox" name="orange" /> $10 - Orange
<input type="checkbox" name="banana" /> $12 - Banana
<input type="checkbox" name="apple" /> $15 - Apple
<input type="checkbox" name="lemon" /> $8 - Lemon
<button type="submit">Submit</button>
</form>
So, this solution will show you only selected items you checkmarked on the page before, just like you asked in your question. If you also want to display all other items you should create an array for both pages. I assume you are still learning PHP and HTML? Do you want that solution also or try it by yourself?
Edit:
Here comes the array solution:
form.php
// We define the array $fruits and assign the price
// to each item as Integer value (therefore without quotation marks):
$fruits = [
'Orange' => 10,
'Banana' => 12,
'Apple' => 15,
'Lemon' => 8
];
<form method="post" action="next.php">
<?php
// With this syntax we say "$key equals $value" ($fruit => $price)
foreach($fruits as $fruit => $price) {
// We use '. $variable .' to merge our variables into HTML
// Since we are in a loop here all the items from the array will be displayed:
echo '<input type="checkbox" name="'.$fruit.'" />
$'.$price.' - '.$fruit;
}
?>
<button type="submit">Submit</button>
</form>
next.php
<table style="width:100%">
<tr>
<?php
foreach($_POST as $fruit) {
echo "<td>".$fruit."</td>";
}
?>
</tr>
</table>
So, we have created an array that holds all the items. This is much more comfortable if you imagine you would list all the available fruits on earth for example or other long lists. With arrays you can also do things like array_sort to maybe sort them by price, etc. So that's super useful.
EDIT 29/03:
This should be in one line and please be aware of the apostroph that is missing:
echo '<input type="checkbox" name="'.$fruit.'" value="'.$fruit.'" />' . $'.$price.' - '.$fruit;
im writing a code in php that need to take a data from html form.
i have few radio bottom and few checkbox bottom.
should i have for every bottom/label do varieble in php?
for example:this is from html
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" name="cats">חתולים<br/>
<input type="checkbox" name="dogs">כלבים<br/>
<input type="checkbox" name="hamsters">אוגרים<br/>
<input type="checkbox" name="goldfish">דגי זהב<br/>
<input type="checkbox" name="human">בני אדם
</td>
</tr>
for php:
if (isset($_POST["name"]))
{
$userName = $_POST["name"];
$userYearOfBirth = $_POST["yearOfBirth"];
$soulmate = $_POST["radio"];
}
It would be better to group the checkbox choices so you can access them as an array on the server in PHP. Additionally, move the name of the choice into the value of the checkbox. The new "name" will be whatever you want to call the checkbox group. I am using Animals for this example:
<form name="your-form-name" action="your-form-action-url" method="post">
<table>
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" value="cats" name="animals[]">חתולים<br/>
<input type="checkbox" value="dogs" name="animals[]">כלבים<br/>
<input type="checkbox" value="hamsters" name="animals[]">אוגרים<br/>
<input type="checkbox" value="goldfish" name="animals[]">דגי זהב<br/>
<input type="checkbox" value="human" name="animals[]">בני אדם
</td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
On the server-side if users select more than one animal, all choices will be available in an array like this:
Array
(
[0] => cats
[1] => dogs
[2] => hamsters
[3] => goldfish
[4] => human
)
If they just select one, it'll still be an array:
Array
(
[0] => cats
)
Either way getting the results as an array lets you do something similar with the results whether they chose one or many choices from the list.
You can loop through all the choices and do whatever you need to with the data:
if (isset($_POST['animals'])) {
$animals = $_POST['animals'];
foreach ($animals as $key => $value) {
// do something with each $value .. maybe add to a database? echo back to user?
}
}
You actually don't need any new variables. You can use $_POST array as the variables.
Example (form side):
<form method="post">
<input type="text" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
echo $_POST['test']; // This will echo the input that named "test".
?>
The example above is valid for every method and input types.
In your case, your checkboxes will output "true" or "false" (Unless you define a value for the checkbox. If you define a value to it, it will output the defined value if the checkbox is checked.).
Example (form side):
<form method="post">
<input type="checkbox" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
if ($_POST['test'] === true)
echo "Yay! The checkbox was checked!";
else
echo "Oops! The checkbox wasn't checked!";
?>
I would like to get the value of what I have echoed in the value of an HTML element but I used a foreach so it retains only the last value of the last loop. I would update the reqStatus depending on its ID through a post method to pass the variables.
HTML w/ foreach:
<form method = "POST" action="">
<table>
<th> Request ID:</th>
<th> Request Status:</th>
<?php
$requests = new OrderRequests();
$requests->getAllOrders();
foreach($requests->orderList as $oList){?>
<tr>
<td>
<input type="hidden" name="reqId" value="<?php echo $oList["request_id"];?>"><?php echo $oList["request_id"];?>
</td>
<td>
<input type="hidden" name ="reqStatus" value="<?php echo $oList["request_status"];?> "><?php echo $oList["request_status"];?>
</td>
<?php if($oList["request_status"]=="Delivered"){?>
<input type="hidden" id="reqIDUpdate" name="reqIDUpdate" value ="<?php echo $oList["request_id"];?>">
<td>
<input type="submit" class="button" value="Confirm Delivery">
</td>
<?php }}?>
</tr>
</table>
</form>
After POST:
if (!empty($_POST["reqIDUpdate"])){
$requestIDUpdate = $_POST["reqIDUpdate"];
global $connection;
$sql = "UPDATE order_request SET request_status = 'Received Delivery'
WHERE request_id = {$requestIDUpdate} ";
mysqli_query($connection, $sql);
unset($_POST["reqIDUpdate"]);
}
Though you are echoing unique values, the value that gets assigned to the form hidden fields (reqId and reqStatus) are getting overwritten by new values in the foreach loop. By the end of the foreach loop, only the last values are saved in these hidden fields.
i have a little problem with my program and not so experienced in php. I want to transfer an array of objects with a html form to my php file. First i will let you take a look on my code:
location.php (with executable forms)
<form action="action/add_items.php" method="POST">
<table border="1" width="20%">
<thead>
<th>
<?= $lang["location_task"][$location->getProperty("location_id")][$location_task->getProperty("location_task_id")]; ?>
</th>
</thead>
<tbody>
<?php
$location_task_items = $location_task->getProperty("location_task_items");
foreach ($location_task_items as $location_task_item) {
?>
<tr>
<td>
<?= $lang["item"][$location_task_item->getProperty("location_task_item_id")]; ?>
</td>
<td>
<?= $location_task_item->getProperty("location_task_item_value"); ?>
</td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td>
<input type="hidden" value="<?php print_r($location_task_items); ?>" name="location_task_items"/>
<input type="submit" value="start"/>
</td>
</tr>
</tbody>
</table>
</form>
You can see that i only print the array in the input hidden value. Is that right?
add_items.php
$location_task_items = $_REQUEST["location_task_items"];
foreach($location_task_items as $location_task_item) {
if($Player_Has_ItemsClass->getObjectByIds($player_id, $location_task_item->getProperty("location_task_item_id")) == null) {
$player_has_items_attributes = array();
$player_has_items_attributes["player_has_items_player_id"] = $player_id;
$player_has_items_attributes["player_has_items_item_id"] = $location_task_item->getProperty("location_task_item_id");
$player_has_items_attributes["player_has_items_item_value"] = $location_task_item->getProperty("location_task_item_value");
$player_has_items = new Player_Has_Items($player_has_items_attributes);
$Player_Has_ItemsClass->insertObject($player_has_items);
} else {
}
}
I only get the array as string and this exception on the foreach in add_items.php:
Invalid argument supplied for foreach()
I also tried it with json_encode and json_decode:
print_r(json_encode($location_task_items))
json_decode($_REQUEST["location_task_items"]);
but only get (object attributes were public):
Call to undefined method stdClass::getProperty()
Thanks for you help :)
In your hidden field use json_encode and then in your destination use json_decode:
<input `type="hidden" value='<?php echo json_encode($location_task_items); ?>' name="location_task_items"/>`
You could do this
<input type="hidden" value="<?php echo serialize($location_task_items); ?>" name="location_task_items"/>
and then
$location_task_items = unserialize($_REQUEST["location_task_items"]);
I am trying to submit multiple arrays with a checkbox form but I am only able to submit one array at the moment, here is what I have so far
In this example I am submitting an array of numbers with the delete[] array, this array gets processed properly, I also want to submit the array condition[] this does not get processed properly, what is the best way to solve this issue?
php code
$catalog = $database->getInventory();
if($catalog){
$numRows = sizeof($catalog);//count
echo "<b>Book Count:</b> ".$numRows."<br>";
echo "<form method='post' action='inventory.php'>";
echo "<table id='example' class='tablesorter' border='0' cellpadding='0' cellspacing='1'>";
echo "
<thead>
<tr>
<th>ISBN</th>
<th>Title </th>
<th>Rank </th>
<th>Condition </th>
<th><input type='checkbox' name='delete' value='all' /></th>
</tr>
</thead>\n";
foreach($catalog as $elem){
echo "
<tr>
<td>".$elem["isbn"]."</td>
<td>".$elem["title"]."</td>
<td>".$elem["rank"]."</td>
<td>".$elem["condition"]."</td>
<td>
<input type='checkbox' name='add[]'
value='".$elem['isbn']."_".$elem['condition']."_"."' />
</td>
</tr>";
}
echo "</table>";
echo "</form>";
}
example html markup
<form method='post' action='inventory.php'>
<table>
<tr>
<td>
<input type='hidden' name='addInventoryBook' value='1'>
<input type='submit' value='Add' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='add[]' value='100001_used' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='add[]' value='100001_new' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='add[]' value='100003_new' />
</td>
</tr>
</table>
</form>
php function
function Inventory(){
if(isset($_POST['addInventoryBook'])){
if(isset($_POST['add']) && is_array($_POST['add'])){
$arr = array();
foreach($_POST['add'] as $checkbox){
$temp = explode("_", $checkbox);
$arr[] = array(
"isbn" => $temp[0],
"condition" => $temp[1],
"sub_condition" => $temp[2]
);
}
$this->addInventoryBook($arr);
}
else{
echo "No values have been set";
}
}
function addInventoryBook($arr){
foreach($arr as $elem){
//if used get sub-category
if($elem['condition']=='used'){
echo $elem['isbn']."-".ucfirst($elem['condition'])
.ucfirst($elem['sub_condition'])."<br>";
}
else if($elem['condition']=='new'){
echo $elem['isbn']."-".ucfirst($elem['condition'])."<br>";
}
}
}
All I want is to basically be able to pass two arrays to my php script
current output
100001
100002
100003
desired output
100001 good
100002 new
100003 new
The problem that you are having, I suspect, is that only the checkboxes that are checked will be passed back to the server, whereas all the hidden fields will always be passed so the lengths of the arrays will differ and the keys wont correspond.
The solution to this is actually relatively simple - you just need to specify the keys for the condition array so you can match the values up again. Something like this:
HTML:
<tr>
<td>
<input type='hidden' name='condition[100001]' value='good' />
<input type='checkbox' name='delete[]' value='100001' />
</td>
</tr>
<tr>
<td>
<input type='hidden' name='condition[100002]' value='new' />
<input type='checkbox' name='delete[]' value='100002' />
</td>
</tr>
PHP:
foreach ($_POST['delete'] as $delete) {
$condition = $_POST['condition'][$delete];
// Do stuff
}
This ties the values in the $_POST['condition'] array back up with the $_POST['delete'] array so everything will match up again.
EDIT
The way the keys are being created above is not great and in retrospect it is the wrong way to do it.
To demonstrate the right way to do it, let's imagine we have the following array, nice and simple:
$books = array(
10001 => 'good',
10002 => 'new',
10003 => 'new',
10004 => 'good'
);
What we need to do is tie up the two inputs that are associated with each book, which means we need a set of key/value pairs that can be matched up. That sounds like an array to me. But unlike the example above, the keys should be irrelevant to the data - they don't need to mean anything, because all we want is the data.
What we need to do is specify every single key explicitly (no stack-style array pushes) and make the keys agnostic of the data they relate to.
We can do this:
$i = 0;
foreach ($books as $isbn => $condition) {
echo "
<tr>
<td>
<input type='hidden' name='condition[$i]' value='$condition' />
<input type='checkbox' name='delete[$i]' value='$isbn' />
</td>
</tr>
";
$i++;
}
...and then, when the form is submitted, we can do this:
// We still base our code on $_POST['delete'] - because this is the array that
// depends on the user input. This time, though, we'll look at the keys as well
foreach ($_POST['delete'] as $key => $isbn) {
$condition = $_POST['condition'][$key];
// Do stuff
}
I'm a little confused about what you are asking, but I think I can simplify this for you. I don't know how you are generating the values for the hidden fields, are they hard coded? Regardless, this system would work much better if it were simplified.
Try this out....
This will combine the info for the numbers and condition, then it will split them on the backend for handling. This way the information is passed at the same time.
<tr>
<td>
<input type='checkbox' name='delete[]' value='100001-good' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='delete[]' value='100002-new' />
</td>
</tr>
<tr>
<td>
<input type='checkbox' name='delete[]' value='100003-new' />
</td>
</tr>
<?php
if(isset($_POST['deleteInventoryBook'])){
if(isset($_POST['delete']) && is_array($_POST['delete'])){
foreach($_POST['delete'] as $checkbox){
$checkbox = explode('-', $checkbox);
echo $checkbox[1];
echo '<br />';
echo $checkbox[0];
echo '<br />';
}
}else{
echo "No values have been set";
}
}
?>
Again, I don't know if this is helpful or not because I was a little misunderstood about what exactly you were trying to achieve, but I hope it was helpful.
You're going to have to find a creative way to pass multiple hidden fields as an array to the PHP handler, or change how that data is collected. A "serialized" array seems to be the best bet.
This StackOverflow answer really outlines what you can do, and should still match your script's behavior. Good luck!