Save variable value in session like cart with single form - php

I have a simple form in sidebar on 5 pages where i have two fields name and price. I want to save its value in session when user will submit the form. when i store its value in session after submit a form then it replace name every time. But i want to store name value like array. If user submit form with name user1 and then submit again with username user2 then i want to show these 2 names in session variable and want to show increment of form submit. Like cart functionality. Is there any way to store these value with a single form. Please help me.
<form id="myform" action="post.php" method="POST">
<div class="row">
<label for="name">Your name:</label><br />
<input id="name" class="input" name="name" type="text" value="" size="30" /><br />
</div>
<div class="row">
<label for="price">Price:</label><br />
<input id="price" class="input" name="price" type="text" value="" size="30" /><br />
</div>
<input id="submit_button" type="submit" value="submit" />
</form>
post.php
session_start();
$_SESSION['cart_items'] = array();
$_SESSION['cart_items'] = $_POST['name'];
foreach($_SESSION["cart_items"] as $cart_item)
{
echo $cart_item;
}

Try to add values to session by
session_start();
foreach ($_SESSION["products"] as $cart_itm) //loop through session array
{
if($cart_item["code"] == $product_code){ //the item exist in array
$product[] = array('name'=>$cart_item["name"], 'code'=>$cart_item["code"], 'qty'=>$product_qty, 'price'=>$cart_item["price"]);
$found = true;
}else{
//item doesn't exist in the list, just retrieve old info and prepare array for session var
$product[] = array('name'=>$cart_item["name"], 'price'=>$cart_item["price"]);
}
}
Add the result by
foreach ($_SESSION["cart"] as $cart_item)
{
echo $cart_item["price"];
$subtotal = ($cart_item["price"]*$cart_item["qty"]);
$total = ($total + $subtotal);
}
echo $total;

Related

Multiple file upload with optional items

I have a form with multiple inputs like this:
<div id="users">
<input type="text" name="title[]" required>
<input type="file" name="images[]">
<input type="text" name="title[]" required>
<input type="file" name="images[]">
<input type="text" name="title[]" required>
<input type="file" name="images[]">
</div>
<input type="button" value="add new user">
<input type="submit" value="submit">
the problem is that selecting image is optional and if the user doesn't select any image for any of titles the posted data would be like this:
title = ["title1","title2","title3"]
images = [image1.jpg,image3.jpg]
the count of users is not fixed and user can add any desired number of titles and images by clicking on the add new user button. so "add new user" button will add a pair of these inputs to users div:
<input type="text" name="title[]" required>
<input type="file" name="images[]">
is there any way to detect if the file is selected or not? or to send a default value for not selected file inputs? I want to set null value for image if no file is selected, like this:
user1:{title="title1",image=image1.jpg}
user2:{title="title2",image=null}
user3:{title="title3",image=image3.jpg}
.
.
.
You can check if particular index is set for file:
var_dump($_POST['title'][0]);
if (isset($_FILES['images']['tmp_name'][0])) {
var_dump($_FILES['images']['tmp_name'][0]);
}
All you have to do is process the 2 arrays and check there is a matching image with each title. If there is not a image for each title, put anything that you like in place of the image name
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$output = [];
foreach( $_POST['title'] as $idx => $title){
$u = $idx+1;
$output['user'.$u] = ['title'=>$title,
'images'=> $_POST['images'][$idx] == '' ? 'NULL' : $_POST['images'][$idx]];
}
$j = json_encode($output);
echo $j;
}
RESULT
{
"user1":{"title":"asss","images":"NULL"},
"user2":{"title":"dd","images":"hammer.jpg"}
}
Thank you everybody, Pavol Velky was right partially, Although the array size is less than the number of inputs, but the browser will set an index to the array, in example if you have two inputs and just select the second one, the array will be like : item:[1:{}] (if you select first one: item:[{}]) and you can check the order by the index number.

PHP: Adding multiple products to post order form

I'm building a sort of php shop that will allow a user to enter amounts for various products and then a form will process the order. There is no payment processing etc. What I am struggling to do is add each product to each amount to send through to the order form as a $_POST variable. Currently my ordered items are a standard form:
<input type="text" id="value" name="ordered-items[]" />
I thought I could add the product ID as a hidden variable, but that will just add it for every product.
<input type="hidden" id="value" name="products[<?php the_id(); ?>]" />
How can I marry up the product to the order quantity and then send that to the order form for processing, this part I can do myself.
Thanks In advance
You can name the product quantity based on it's ID like this:
<input type="text" name="item[<?php the_id(); ?>]" />
You can then access the product quantities on the server side using for each:
foreach($_POST as $index => $value){
// $index is product id and $value is product quantity
}
Why not put the quantity in a separate input field. In case of a normal text field the visitor can then even change the quantity:
<input type="text" id="item1" name="ordered-items[]" /><input type="text" id="qty1" name="quantity[]" />
<br>
<input type="text" id="item2" name="ordered-items[]" /><input type="text" id="qty2" name="quantity[]" />
<br>
<input type="text" id="item3" name="ordered-items[]" /><input type="text" id="qty3" name="quantity[]" />
In php you can process the data like this:
<?php
$items = $_POST['ordered-items'];
$quantities = $_POST['quantity'];
for($i = 0; $i < count($items); $i++) {
echo $items[$i] . ' has quantity ' . $quantities[$i];
}

Need to carry check-box data from one page to another using PHP

I am new to php and am not quite clear on what to do to carry my information from the first page to the next and then submit it to my email when they are done filling out contact information.
I need the script to work as follows:
Step1: User clicks the input check-boxes for the field they want that is stored in an array
ex:
< input type="checkbox" name="Sound[]" value="item1" > item1
and clicks a button i have written as
< input type="image" name="Submit" class="" alt="" src="images/contact1.png" border="0" >
Step2: The information from the check-boxes they have clicked needs to be carried over to the next page where they will fill out their contact info. Name email phone etc.
ex:
<tr>
<td valign="top">
<label for="telephone">Telephone Number *</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30" style="margin-bottom: 10px;">
</td>
</tr>
Step3. All of this information should be sent to my email upon button press for me to contact them :D
<tr>
<td colspan="2" style="text-align:center;">
<input type="image" name="Contact" class="contactbutton" alt="" src="images/contact.jpg"/>
</td>
</tr>
I can pull the information from my inputs but do not know how to carry to the next page!
Can I do it all in the same php script? or does each page need a different php script?
Please help!
Thanks Paul
you can do it with a form and send it to the page2.php. value will be stored in
$_POST['S'] for the checkbox
<form action="page2.php" method="post">
<input type="checkbox" name="S" value="item1" > item1
<input type="SUBMIT" >
</form>
------------------
page2.php
echo($_POST['S']); // will be item1
$_SESSION array is better. to use it you need to put session_start(); at start of
every page that will use your $_SESSION variable i.e
session_start();
if(isset($_POST['S'])){
$_SESSION['h'] = $_POST['S'];
echo($_SESSION['h']); } //output value in checkbox
?>
<html><body>
<form method="post">
<input type="checkbox" name="S" value="item1" > item1
<input type="SUBMIT" value="item1" >
Once this script is run you can accesS value in $_SESSION['h'] in other pages.
the data will be deleted when you close browser.
----------------------------------
page2.php
<?php
session_start();
if(isset($_SESSION['h'])){ //check if $_SESSION['h'] has been set a value
echo $_SESSION['h']; //output value stored in var
}
?>
You will ultimately still require the use of POST data to get the checkbox status from your page.
Page 1:
<?php
session_start();
// If postdata is received then redirect to next page
if(isset($_POST['Sound'])) {
$_SESSION['Sound'] = $_POST['Sound'];
header('Location: http://www.example.com/page2.php');
exit;
}
?>
<form method="post" action="page1.php">
Sound? <input type="checkbox" name="Sound" value="item1"><br>
<input type="submit">
</form>
Page 2:
<?php
session_start();
// If postdata is received then redirect to next page
if(isset($_POST['telephone']) && isset($_POST['email'])) {
$_SESSION['telephone'] = $_POST['telephone'];
$_SESSION['email'] = $_POST['email'];
header('Location: http://www.example.com/page3.php');
exit;
}
?>
<form method="post" action="page2.php">
<!-- If you want to output the previously saved data in a disabled item -->
Sound? <input type="checkbox" name="Sound" value="item1" disabled="disabled" <?php if($_SESSION['Sound'] == 'Yes') echo('checked="checked"'); ?>>
Telephone: <input type="text" name="telephone" value=""><br>
Email: <input type="email" name="email" value=""><br>
<input type="submit">
</form>
And so on and so forth for your next pages
This does not include the code for generating the e-mail via PHP but is intend to show you how you can take the form input/checkbox selections and store there values to a SESSION ARRAY. Note that in this example: The form is submitting to itself by leaving the action="" blank, but normal would submit to a external PHP file for parsing/handling.
Also, im choosing to create a random number to represent the visitor to the form if not specifically set by $_POST['user']
<?php session_start();
if (!isset($_SESSION['user'])) {$_SESSION['user']=rand(10,700);}
if (isset($_POST['user'])) {$id=$_POST['user'];} else {$id=$_SESSION['user'];}
?>
<form action="" method="post">
Sound 1:<input name="cb1" type="checkbox" value="sound1"><br>
Sound 2:<input name="cb2" type="checkbox" value="sound2"><br>
Sound 3:<input name="cb3" type="checkbox" value="sound3"><br>
<input type="submit" name="submit" value="submit"><br><br>
<?php
if (isset($_POST['submit']) && $_POST!=="") {
foreach($_POST as $key => $value) {
$_SESSION['visitor']['sounds'][$id]=array(
'selects'=>$_POST['cb1'].",".$_POST['cb2'].",".$_POST['cb3']
);
};
echo "For user ID:".$id." We echo the comma delimited stored SESSION array: ".$_SESSION['visitor']['sounds'][$id] ['selects'];
echo "<br><br>";
// Option 2 Explodes the comma delimited ['selects'] field to handle each choice seperately
$choice = explode(",",$_SESSION['visitor']['sounds'][$id] ['selects']);
echo "For an alternative, we EXPLODE the stored 'selects' field of the SESSION ARRAY and can then echo each out seperately"."<br><br>";
echo "User ".$id." Option 1 value was: ".$choice[0]."<br>";
echo "User ".$id." Option 2 value was: ".$choice[1]."<br>";
echo "User ".$id." Option 3 value was: ".$choice[2]."<br>";
echo "<br><br>";
echo "A last example we loop through the EXPLODED values and echo only those that were selected (ie: had a value)"."<br>";
foreach ($choice as $key => $value ) { if ($value!=="") {echo "Selection: ".$value."<br>";} }
}
?>

how to retain the state of a checkbox after server side validation in php?

I have a form with various fiedls (Name, email, password, etc..). It also has a set of 5 check-boxes. As i have to update a database i prefer doing server-side validation and i am using php.
If a validation error occurs, the error is displayed on the top of the page along with the form and the previously entered data in the text fields. I am not able to retain the state of the checkboxes and radio buttons. The all revert back to being not selected. What should i do to retain the state of checkboxes and radio buttons?
The form looks something like..:
Password:<input type="text" name="password" size="16" maxlength="9" value="<?php echo $_POST['password']?>"/>
Retype Password:<input type="text" name="repassword" value="<?php echo $_POST['repassword']?>"/>
Select:<br />
<input type="checkbox" name="option1" value="on1" id="opt1"/> <label for="opt1">Option1</label><br />
<input type="checkbox" name="option2" value="on2" id="opt2"/> <label for="opt2">Option2</label><br />
<input type="checkbox" name="option3" value="on3" id="opt3"/> <label for="opt3">Option3</label><br />
<input type="checkbox" name="option4" value="on4" id="opt4"/> <label for="opt4">Option4</label><br />
<input type="checkbox" name="option5" value="on5" id="opt5"/> <label for="opt5">Option5</label><br />
Mobile No:<input type="text" name="mobileno" maxlength="10" value="<?php echo $_POST['mobileno']?>"/>
What you're talking about is Sticky Forms. You can implement sticky forms in many ways, my choice is to use session. If there is an error in your validation, simply dump everything in your POST data into session. On your form page, check to see if the value is set in session and set the default value of the form control it if it is:
Validation Page:
<?php
session_start();
if(/** some error condition **/) {
foreach($_POST as $k => $v)
$_SESSION['sticky_'.$k] = $v;
header('Location: http://site.com/yourform.php');
exit();
}
?>
Form Page:
<?php session_start(); ?>
<input type = "checkbox" name = "option1" value = "on1" id = "opt1" <?php
if(isset($_SESSION['sticky_option1']))
echo('checked = "checked");
?>/>
Example TextBox: <input type = "text" name = "textBoxName" <?php
if(isset($_SESSION['sticky_textBoxName']))
echo('value = "' . $_SESSION['sticky_textBoxName'] . '"');
?>
...
<?php
// Erase the POST values from session after the HTML is constructed.
foreach($_SESSION as $k => $v)
if( strpos($k, 'sticky_' !== false )
unset($_SESSION[$k]);
?>
Add a checked attribute to any checkbox who's value is in the submitted data.

Form with variable input values PHP

I have a form which has variable input values .For example one customer has bought 5 items so all of them show another customer has bought 3 items so only three items show up.All these values are based on database
<form id="customer" class="customer" method="post" action="">
<input type="text" name="customer1" value="" >
<input type="text" name="customer2" value="" >
<input type="text" name="customer3" value="" >
</form>
Now my question how do i process a form like this where every time the number of post variables is different.
<input type="text" name="customer[]" value="" >
Something like:
$products = array();
foreach ($_POST as $key => $value) {
array_push($products, $key, $value);
}

Categories