Relating values in a PHP multiple checkbox array - php

I searched and can't find an answer to this and nothing I try works. In this form, for each image (pix) and there the user enters the number of copies to be produced.
I know how to build the array for each individually when the submit button is clicked but I can't get both arrays to relate to each other. I want to produce something like: 01.jpg - 3 copies, 02.jpg - 1 copy etc etc.
How can I achieve this?
Thanks
This is my form:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg">
<input type="checkbox" name="pix[]" value="01.jpg_album">
<input type="text" name="quantity[]">
<img src="02.jpg" alt="02.jpg">
<input type="checkbox" name="pix[]" value="02.jpg_extra">
<input type="text" name="quantity[]">
<img src="03.jpg" alt="03.jpg">
<input type="checkbox" name="pix[]" value="03.jpg_extra">
<input type="text" name="quantity[]">
<input type="submit" name="submit">
</form>
This is how I extract the values returned:
echo implode('<br>', $_POST['pix']);
echo implode('<br>', $_POST['quantity']);
EDITED: FURTHER to my question above and in response to the second code posted by Rajdeep ... I've separated the two processes. The first was to determine whether the client wanted the image for his wedding album, so I did:
$arr = array("01", "02", "03");
echo "<h3>Images required for album: </h3>";
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg";
if(isset($_POST[$value]) && !empty($_POST[$value])){
echo $var."<br />";
}//endif
} //endif
}// end foreach
This output was:
03.jpg
04.jpg
23.jpg
etc
Then, I wanted to know if he needed any additional individual prints and this code (sort of) worked for that:
echo "<h3>Extras required: </h3>";
$noextras = false;
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg - ";
if(isset($_POST[$value . "_extra"]) && !empty($_POST[$value . "_extra"])){
$sum = $_POST[$value . '_extra'];
if($sum == 1) {
$var .= $sum ." copy <br />";
} else {
$var .= $sum . " copies <br />";
}
echo $var;
} else if(empty($_POST[$value . "_extra"])) { $noextras = true; }
} //endif in_array
}// end foreach
if($noextras) { echo "No extra copies needed.";}
And the output from this was something like
03.jpg - 5 copies
04.jpg - 2 copies
23.jpg - 1 copy
I then discovered a snag. This permitted extra copied to be selected for ONLY for images that were selected for inclusion in the album. I have tried various variations on the code and I am coming up with a blank.
So, I've changed this to a two step process. First page, the person selects the images for the album, which when submitted go to a confirmation page to show what had been selected. Once he clicks the 'confirm' button an email goes to me and him.
Clicking the confirm button also goes to a Thank You page which then refreshes into the second page for ordering individual prints. Here he can select how many copies of a print he needs and this works well with Rajdeep's first 'merged' code BUT it only works for one selection.
I've expanded the selection and this is where I am currently having trouble. He has a choice to decides how many copies he needs of each of the four different sizes available (7x6, 9x5, 10x8, 12x8). I am able to process one size only but am having trouble with expanding it to four inputs.
Any suggestions?
Thanks.

Instead of two different <input> tags with checkbox and text attribute, use only one <input> with number attribute for each image. And make the name attribute as the name of your image, like this:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg" />
<input type="number" name="01" min="0" />
<img src="02.jpg" alt="02.jpg" />
<input type="number" name="02" min="0" />
<img src="03.jpg" alt="03.jpg" />
<input type="number" name="03" min="0" />
<input type="submit" name="submit" value="submit" />
</form>
And this is how you can process the form,
if(isset($_POST['submit'])){
foreach($_POST as $key => $value){
if($key == "submit"){
continue;
}
if(!empty($value)){
$var = $key . ".jpg - " . $value;
if($value == 1){
$var .= " copy";
}else{
$var .= " copies";
}
$var .= "<br />";
echo $var;
}
}
}
A sample output would be like this:
01.jpg - 3 copies
02.jpg - 1 copy
03.jpg - 5 copies
Edited:
Based on your requirement, use <input type="checkbox" name="xx" value="xx" /> for selecting the image(i.e when user wants this image to be included in photo album) and use <input type="number" name="xx_extra" min="1" /> for keeping track of how many extra copies of this image user wants.
So your HTML code should be like this:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg" />
<input type="checkbox" name="01" value="01" />
<input type="number" name="01_extra" min="1" />
<img src="02.jpg" alt="02.jpg" />
<input type="checkbox" name="02" value="02" />
<input type="number" name="02_extra" min="1" />
<img src="03.jpg" alt="03.jpg" />
<input type="checkbox" name="03" value="03" />
<input type="number" name="03_extra" min="1" />
<input type="submit" name="submit" value="submit" />
</form>
And this is how you can process the form,
<?php
if(isset($_POST['submit'])){
$arr = array("01", "02", "03");
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg - ";
if(isset($_POST[$value . "_extra"]) && !empty($_POST[$value . "_extra"])){
$sum = $_POST[$value . '_extra'] + 1;
$var .= $sum . " copies <br />";
}else{
$var .= "1 copy <br />";
}
echo $var;
}
}
}
?>

Related

Adding arrays inside an array from input PHP

My goal: I wanted to make a list system that stores an array that has 3 values...
"Product's Name",
"Product's Price",
"Amount of Products".
And I want the user to keep adding products and be able sum it all up by multiplying the price by products and summing it all together if there's two or more products in the array.
Expectations:
"Milk",
2.99,
40
"Apples",
3.00,
5
My problem is the array input is replacing index 0.
Result:
Milk
2.99
40
I tried adding the other value, it replaces index 0.
I need some help to understand this problem.
<html>
<body>
<input id="inventory" name="p-name" type="text" placeholder="product name">
<input id="inventory" name="p-price" type="text" placeholder="product name">
<input id="inventory" name="p-amount" type="text" placeholder="product name">
<input id="inventory" name="s-name" type="text" placeholder="product name">
<input id="inventory" name="s-price" type="text" placeholder="product name">
<input id="inventory" name="s-amount" type="text" placeholder="product name">
<input type=submit name=submit[AddToList] value='Add to list'>
<input type=submit name=submit[ClearAllList] value='Clear All List'>
<?php
$listOfInventories = array();
if (isset($_POST["submit"])) { // Checks if user clicked btn.
$sub = $_POST["submit"];
$time = $_POST["time"];
$pName = $_POST["p-name"];
$pPrice = $_POST["p-price"];
$AmountOfProducts = $_POST["p-amount"];
$sName = $_POST["s-name"];
$sPrice = $_POST["s-price"];
$TimesWorkersLabored = $_POST["s-amount"];
if (isset($sub["AddToList"])) {
echo " Added to list <br>";
array_push($listOfInventories, array($pName, $pPrice, $AmountOfProducts)) ;
foreach ($listOfInventories as $value) {
foreach ($value as $x) {
echo $x;
}
}
echo count($listOfInventories);
// Save something;
} elseif (isset($sub["ClearAllList"])) {
$listOfInventories = [];
// Delete something
}
?>
</body>
</html>
Adding first product
Adding second product
Edit1: Possibly the fault is the initialization array, but where should I put it? It might not work before the array_push.
Please use SESSION to do what you want (this is a rather standard way to handle things like "shopping cart")
Hence, try something like $_SESSION["listOfInventories"] = array(); and then array_push($_SESSION["listOfInventories"], array("Apple", 10.5, 1)) ;
Please try to run the following PHP script, and RELOAD to see the effect - it will preserve the data and add more item(s)
<?php
session_start();
if (!isset($_SESSION["listOfInventories"]))
{$_SESSION["listOfInventories"] = array();}
array_push($_SESSION["listOfInventories"], array("Apple", 10.5, 1)) ;
echo count($_SESSION["listOfInventories"]);
echo "....<br>";
array_push($_SESSION["listOfInventories"], array("Orange", 10.5, 1)) ;
echo count($_SESSION["listOfInventories"]);
echo "....<br>";
?>
Use method="POST", put your Type="submit" attribute to Submit in Double Quote and Value="".. also put your } at the end of the if statement, add session_start() into the Login file and call only the number of inputs in the Field. use Localhost to store your Timestamp.

how to add up values from checkboxes in php

for training purposes i've made a little code which outputs the value of a checkbox. this works well, but since i am able to check multiple checkboxes i want them to add up. this is my code;
<table border=0 cellpadding=0 cellspacing=0 width=100%>
<form name="orderform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="checkbox" name="korting" value=15 /> Student 15% <br>
<input type="checkbox" name="korting" value=10 /> Senior 10% <br>
<input type="checkbox" name="korting" value=5 /> Klant 5% <br>
To output the value ive written;
<?php
if(isset($_POST["korting"]))
{
if($_POST["korting"]==15)
{
echo ("15 procent korting");
}
else if ($_POST["korting"]==10)
{
echo ("10 procent korting");
}
else if($_POST["korting"]==5)
{
echo ("5 procent korting");
}
else if(isset($_POST["korting"]) && (isset($_POST["korting"])))
{
if($_POST["korting"]==25)
{
echo ("25 procent korting");
}
}
}
?>
As long as one checkbox is checked, everything works fine. as soon as is check more than one it only uses the last one. I've tried multiple thing like:
else if(isset($_POST["korting"]) && (isset($_POST["korting"]))
{
echo ("25 procent korting");
}
and
else if($_POST["korting"=15] && $_POST["korting"]=10)
{
echo ("25 procent korting");
}
both do not give an error on the page but also don't work. I know it's probably better to use completely different approach but for now this is how the book teaches me
Greetings,
Lennart
What you need is an array. The checkboxes would look like this:
<input type="checkbox" name="korting[]" value="15" />
<input type="checkbox" name="korting[]" value="10" />
$_POST['korting'] would then be an array of values, like this:
array(
0 => 15,
1 => 10
)
You can loop through them to print out the values:
foreach ($_POST['korting'] as $korting_value) {
echo $korting_value . "<BR>";
}
If you want to add up the values, you can use array_sum:
echo array_sum($_POST['korting']);

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);
}

How to pass mutiple value to another PHP page using checkbox?

DEMO.PHP
<form action = "test.php" method="post">
<input type="checkbox" name="vehicle[]" value="'Peter'=>'35'">I have a bike<br>
<input type="checkbox" name="vehicle[]" value="'Ben'=>'37'">I have a car <br>
<input type="submit" value="Submit">
</form>
test.php
<?php
if(isset ($_POST["vehicle"]))
{
$v = $_POST["vehicle"];
foreach($v as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
}
?>
My $x didnt get Peter or Ben?
How can I get the key and value separately?
If you name your fields ending in [], then PHP will construct a regular array from them.
Using => in the value will have no special meaning.
If you want to specify the key names that PHP will parse the form data into, then you do so in the name:
name="vehicle[Peter]" value="35"

How to receive a batch of checkbox data in PHP?

The key code is:
while ($row= mysql_fetch_array($result, MYSQL_ASSOC))
{ $id=$row[id];
$html=<<<html
<tr><td>
<input style="float:left" type="checkbox" name="mycheckbox[]" value="$id">
<span style="float:left">$row[content]</span>
<span style="color:black;float:right">$row[submitter]</span></td></tr>
html;
echo $html;
}
There are many checkboxes.
How to receive these checkbox values in another PHP file?
You know, you need to name these checkboxes so a PHP file can receive these values on the other side. But how to name these checkboxes? If I name 1,2, 3,...,how can I associate them with $row[id]?
You need to give them names - you can either do it like this:
<input style="float:left" type="checkbox" id="$id" name="$id" value="true">
or like this to get an array:
<input style="float:left" type="checkbox" id="$id" name="myBoxes[$id]" value="true">
You can then check isset($_POST[$id]) or isset($_POST['myBoxes'][$id])
Name your checkboxes so you can easily identify them.
eg
$CheckBoxHTML = "<input type='checkbox' name='check_$row[id]' value='YES'>Check This";
then in your recieving php file you can find all checkboxes by
foreach ($_POST as $key => $value)
{
if (strpos($key,'check_') !== false)
{
list($tmp, $ID) = split('_', $key);
$CheckedValues[] = $ID;
}
}
That will pull out all your checked ids.

Categories