Auto-Increment Form Input Names With $_SESSION - php

I want to use PHP $_SESSION to access user form-inputted data. The flow looks like this:
STEP 1
User fills out form.
<form method="post" action="review.php">
<input type="text" name="length">
<input type="text" name="width">
<input typ="text" name="quantity">
<input type="submit" value="submit">
</form>
STEP 2
Form data is submitted and 'review.php' converts from POST to SESSION. User reviews form details and adds item to cart.
STEP 3
Item is added to PayPal Shopping Cart. User decides he wants to add another item so user clicks on "continue shopping" and returns to STEP 1.
STEP 1
User fills out form details. Except this time, I want the input name to auto-increment.
For example:
<input type="text" name="length2">
<input type="text" name="width2">
<input type="text" name="quantity2">
And I want it to auto increment however many number of times the user adds new items to the cart.
<input type="text" name="length3">
<input type="text" name="length4">
<input type="text" name="etc">
Usual flow continues... STEP 2 ---> STEP 3
After successful payment in STEP 3, user will be redirected to a new page.
STEP 4(newPage)
All of the purchased items' details will be displayed on this page in order and with the same group. For example, (length, width, quantity) then (length2, width2, quantity2) and so on and so forth. They will each be displayed in different forms.
Those forms will also include <input type="file"> so that the user can upload a file for each form. Each form represents a purchased item.
Once the user uploads files to each corresponding form, they will be submitted to a database.
QUESTION
How can I make the input names auto increment preferably with PHP,
and of course whilst using $_SESSION? I would like the name to
return to its original name after the user's session. So let's say
that same user wanted to order the next day and he ordered 5 items,
the input names would span to 5 (length, length2,..., length5).
How can I display all of the user inputted data in each respective
form(see STEP 4)?
I know I have to do all of the back-end stuff on PHP($_SESSION, forms, etc) but if someone has a jQuery solution for the auto increment and showing all of the data in the end I'm all for it.
Here's What I Was Working With
Tried to use this to display the data with the incremented names but couldn't figure out a solution.
<?php
session_start();
?>
<form>
<?php
$size = $_SESSION['size'];
$variables = array("$size");
$i = 1;
foreach ($variables as $var ) {
$name = "txt".$i;
echo "<input type='text' name='".$name."' value='".$var."' />";
$i++;
}
?>
</form>
Some of you might bring up PayPal IPN. I created an IPN listener as well but it doesn't get called via sandbox. A user on here posted that his IPN listener didn't work on sandbox either but when he went live via paypal.com it did work. Could be the case with mine too, but I want to go ahead and start selling so I need a different approach. Even if my IPN listener does work via paypal.com, I can't risk going live with it without being 100% sure. So if I can use this method for now until I can confirm that my listener works I will do it.
As always I am very grateful for your guys' help.

I actually figured this out a while back. Here's the code I am using:
<?php
if(isset($_POST['submit'])){
$_SESSION['invoice'] = $_POST['invoice'];
$invoice_no = $_SESSION['invoice'];
$decal = array(
'length' => $_POST['os0'],
'width' => $_POST['os1'],
'color' => $_POST['os2'],
'quantity' => $_POST['os3'],
'price' => $_POST['price'],
'submit' => $_POST['submit']
);
$_SESSION['order'][] = $decal;
$i = 0;
}
if(isset($_SESSION['order'])){
foreach($_SESSION['order'] as $sav) {
$i++;
?>
<input type="hidden" name="on0_<?php echo $i; ?>" value="Length">
<div class="decalName">
<label>Custom Decal <?php echo $i; ?></label>
</div>
<div class="label-input">
<label>Length</label><input type="text" name="os0_<?php echo $i; ?>" id="length" size="2" class="num" value="<?php echo $sav['length']; ?>" readonly>
</div>
<input type="hidden" name="on1_<?php echo $i; ?>" value="Width">
<div class="label-input"><label>Width</label><input type="text" name="os1_<?php echo $i; ?>" id="width" size="2" class="num" value="<?php echo $sav['width']; ?>" readonly>
</div>
<input type="hidden" name="on2_<?php echo $i; ?>" value="Color">
<div class="label-input">
<label>Color</label><input type="text" name="os2_<?php echo $i; ?>" value="<?php echo $sav['color']; ?>" readonly>
</div>
<div class="label-input">
<label>Quantity</label><input type="text" name="os3_<?php echo $i; ?>" size="2" class="num" id="quantity" value="<?php echo $sav['quantity']; ?>" readonly>
</div>
<input type="hidden" name="on3_<?php echo $i; ?>" value="quantity">
<input type="hidden" class="num" value="0.20">
<div class="label-input">
<label>Price $:</label><input type="text" class="tot" name="price" value="<?php echo $sav['price']; ?>" readonly>
</div><!--end label-input-->
<?php
}
?>

Related

Passing input values using post

I am trying to pass the value of <input id="ids" type="hidden" name="ids" value="<?php echo $key['product_ID'];?>"> to the exchange.php page. Lets say i have apple | 1 , orange | 2, pineapple | 3. However, whenever i try to submit the values to another page, I am getting the 3 as the echo value of $product. When i try to remove the type="hidden", I get the correct value but when I try to submit, it turns out to be a different value.
<form action="exchange.php" method="post">
<div class="row">
<?php $query="SELECT * FROM Product" ; $data=$ MySQLi_CON->query($query);
foreach ($data as $key ) { ?>
<strong>Name: </strong>
<?php echo $productname=$ key[ 'product_Name'];?>
<input id="ids" type="hidden" name="ids" value="<?php echo $key['product_ID'];?>">
<strong>Status: </strong>
<strong>Action: </strong>
<input type="submit" value="Exchange" name="exchange_submit" class="btn btn-info btn-xs">
<input id="id" name="id" type="hidden" value="<?php echo $id; ?>">
<?php } ?>
</div>
</form>
exchange.php
<?php
$id = $_POST['id'];
$product = $_POST['ids'];
echo $id;
echo $product;
exit;
?>
<?php echo $productname=$ key[ 'product_Name'];?>
//is it working not showing error
Whenever you execute a foreach loop, it will store the last output of the Database table in the hidden input of yours, and that's why no matter any input you give, it will take 3 as the id of the product.Try using a tag also.
You are using foreach for products so I consider you've more than one products.
but when you doing this you are overwriting the $_POST['ids'].
<input id="ids" type="hidden" name="ids" value="<?php echo $key['product_ID'];?>">
thats why its showing last product_ID present in table.

Simple php paypal ipn for wordpress

This is my first time trying to integrate paypal into a wordpress site - so I might need a bit of hand holding. I'm building a custom plugin for a client where the admin creates booking forms for events and assigns them to users. The user can then log in and see their assigned booking forms and fill them out. Once filled out, the user can then pay the price of their booking.
Let say the user has filled out their booking form and is now ready to pay for their booking, they click on "pay" and are taken to a payment page (www.yoursite.com/deposit/?booking-id=xxx) which is essentially just a message and a pay button and hidden form fields for paypal. Here is the php for that page:
<?php
$paypal_url='https://www.sandbox.paypal.com/cgi-bin'; //
$paypal_id='malik#thedistractionsband.co.uk'; // Business email ID
$booking_form_id = get_query_var( 'booking-id' );
$current_user = wp_get_current_user();
?>
<?php
// The Query
$bookings_query = new WP_Query(
array(
'post_type' => 'bookings',
'p' => $booking_form_id
)
);
// The Loop
if ( $bookings_query->have_posts() ) {
while ( $bookings_query->have_posts() ) {
$bookings_query->the_post();
?>
<h2>Pay Deposit</h2>
<p>Hello <?php echo $current_user->display_name; ?> blah blah blah</p>
// Paypal form
<form action="<?php echo $paypal_url; ?>" method="post" name="frmPayPal1">
<?php
$total_amount = get_post_meta( $bookings_query->post->ID, 'wedding_price', true );
$deposit_amount = $total_amount*0.2;
?>
<input type="hidden" name="business" value="<?php echo $paypal_id; ?>">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="item_name" value="<?php echo get_post_meta( $bookings_query->post->ID, 'wedding_name', true ); ?> - 20% Deposit">
<input type="hidden" name="item_number" value="DISTR<?php echo $booking_form_id; ?>">
<input type="hidden" name="credits" value="510">
<input type="hidden" name="userid" value="<?php echo $current_user->ID; ?>">
<input type="hidden" name="amount" value="<?php echo $deposit_amount; ?>">
<input type="hidden" name="cpp_header_image" value="http://www.thedistractionsband.co.uk/files/2015/08/LOGO-1.1-1024x304.png">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="currency_code" value="GBP">
<input type="hidden" name="handling" value="0">
<input type="hidden" name="cancel_return" value="<?php echo get_site_url()."/payment-cancel/"; ?>">
<input type="hidden" name="return" value="<?php echo get_site_url()."/my-bookings/"; ?>">
<input name="notify_url" value="<?php echo DISTRACTIONS_LOGIN_PLUGIN_URL ?>includes/payments/paypal-ipn.php" type="hidden">
<input type="submit" border="0" name="submit" value="Pay Now" alt="PayPal - The safer, easier way to pay online!">
<div class="cards"><i class="fa fa-cc-amex"></i> <i class="fa fa-cc-mastercard"></i> <i class="fa fa-cc-visa"></i> <i class="fa fa-credit-card"></i> <i class="fa fa-cc-paypal"></i></div>
</form>
<?php
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
echo '<p>No bookings found</p>';
}
?>
This all works fine, and actually payments go through fine. I'm now trying to work on the paypal-ipn.php file which is where I want to create communications with paypal and add an entry to the post_meta database table when payment is successful.
So far I don't have much, but here is my paypal-ipn.php
<?php
global $wpdb;
update_post_meta(52, 'deposit_paid', 1);
?>
I'm hoping that this would update deposit_paid to '1' (for post_id 52 - which I will dynamically change to the booking that has been paid for....once I've got this working).
Currently it does nothing, Am I doing something wrong here?
You have a few options here - the easiest (as its just a php page) is to add the following:
// Make wordpress functions available - so we can write to the db etc
require_once realpath('/wp-load.php');
With the correct relative path to the wp-load.php file (its in the root of WordPress).
You need this to enable the functions and get update_post_meta(); to work etc...
When developing you should have:
define('WP_DEBUG', true);
Set up in your wp-config.php as this will alert you to problems.
Option #2 is to make a function and hook the into a WordPress hook when the user submits the form. This is more complex and I feel not what you are after.

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 do I determine which dynamically-generated submit button was clicked in my PHP form?

I want to edit a dynamically-generated form (meaning: I don't know how many rows will be generated). This content is generated within a while loop, and the HTML generated has creates buttons of input-type=submit, generating as many identically-named buttons as there are iterations in the loop.
Of the generated buttons, I want to know which submit button has been clicked, in order to provide the user the same form for which it has been clicked. Disregard the name of the database and password to connect it; the connectivity is fine.
Feel free to suggest any new method to achieve the desired functionality.
The code is as follows:
echo "you have reached your travel details page. your recent travelling details are as follows".'</br>';
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE emailid='{$_SESSION['username']}' ORDER BY dep_date DESC";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
?>
<h1>Your travel details are:-</h1>
<form name="showtraveldet" METHOD="POST" action="edittraveldet.php">
<table border="1">
<tr>
<th>Starting point</th><th>Ending point</th><th>No of passengers</th><th>Expected fare</th><th>Departure date</th>
<th>Departure time</th><th>Arrival Date</th><th>Arrival Time</th><th>Car Model</th><th>Car number</th>
<th>Who is driving</th><th>Driver's license number</th>
</tr>
<?php
while ($row=mysqli_fetch_array($result))
{
$tid=$row['travel_id'];
echo "the value of tid is '{$tid}'";
echo'<tr><td>'.$row['start_point'].'</td><td>'.$row['end_point'].'</td><td>'.$row['no_of_pass'].'</td><td>'.
$row['exp_fare'].'</td><td>'.$row['dep_date'].'</td><td>'.$row['dep_time'].'</td><td>'.$row['arr_date'].'</td><td>'.$row['arr_time'].'
</td><td>'.$row['car_model'].'</td><td>'.$row['car_no'].'</td><td>'.$row['who_is_driving'].'</td><td>'.$row['driver_license_no'].'</td>
<td><input type="submit" name="edit" value="Edit"></td></tr><input type="hidden" name="travelid" value="'.$row['travel_id'].' ;?>">';
}
edittraveldet.php :-
$travelid=$_POST['travelid'];
echo "the travel id in the variable is $travelid and got the value from '{$_POST['travelid']}'";
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE travel_id='{$travelid}'";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
mysqli_close($dbc);
$row=mysqli_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validatewheregoing()" name="wheregoing">
<h1> Enter your travelling details so that other travellers can join you</h1>
<fieldset>
<legend> Travelling details </legend>
Start Point: <input type="text" name="start" value="<?php echo $row['start_point']; ?>"/><br />
End point: <input type="text" name="end" value="<?php echo $row['end_point']; ?>"/><br />
Passengers allowed: <input type="number" name="noofpass" value="<?php echo $row['no_of_pass']; ?>"/><br />
Expected Fare per passengers in rupees:<input type="number" name="fare" value="<?php echo $row['exp_fare']; ?>"/><br />
Departure Date:<input type="date" name="depdate" value="<?php echo $row['dep_date']; ?>"/><br/>
Departure time:<input type="time" name="deptime" value="<?php echo $row['dep_time'] ;?>"/><br/>
Arrival Date:<input type="date" name="arrdate" value="<?php echo $row['arr_date']; ?>"/><br/>
Arrival time at destination:<input type="time" name="arrtime" value="<?php echo $row['arr_time']; ?>"/><br/>
Car Model and name:<input type="text" name="cardet" value="<?php echo $row['car_det']; ?>"/><br/> <!--make this as a dropdown box for better database matching-->
Car Number:<input type="text" name="carno" /><br/><input type="checkbox" name="taxi" value="check this box if pooling a taxi">
Is the car self driven or driven by driver?<input type="radio" name="drivedet" value="Selfdriven" checked=""/>Self Driven<input type="radio" name="drivedet" value="driverdriven" />Driver driven<br />
Driver's License number<input type="text" name="licence_no"/></br>
<input type="checkbox" name="taxi" value="check this box if pooling a taxi"></br>
<input type="hidden" name="travelid" value="<?php echo $travelid ;?>" />
<input type="submit" value="invite travellers" name="editwheregoing"/>
</fieldset>
</form>
If only you can change your code, I would suggest you put the form tag itself in the while loop, each having the same action pointing to the same url but submitting different information to the destination page. This way you don't have to worry about the button clicked
while($row=mysqli_fetch_array($result))
{
//<form action="sameactionurl.php" name="form_1">
//<input type="hidden" name="travelid" value="$row['travelid']" />
//</form>
}
Another solution, if you don't want to change your code is use JavaScript to set a common hidden field to the value of the current ID before submitting the form
Name your submit buttons in a standard fashion and append a 3-digit number to the end, "button_XXXX_###" where ### is the number and XXX was the original name of your button.
After submission, check your request parameters for all variables starting with name "button_XXXX", and split the actual name "button_XXXX_####" by '_' character, and the "###" suffix will reveal the number of the button pressed.
It might be easier to create a form for each row instead, though.

PHP Includes after submitting a form

I'm a bit of a noob when it comes to PHP and forms but I will do my best to explain.
What I am trying to do is create a series of forms that are included in a content container. The user fills out form#1, clicks 'submit' and moves on to fill in form#2 and so on. The data from each form is sent to the next form and is stored in hidden fields and once form#3 is completed the data is all inserted into a MYSQL database.
All of this works fine so far. The problem I am having is that I can't seem to get the submit buttons to work as intended. What I had envisioned is that the user would navigate to 'blah.com/recruit.php?p=form1' and fill out form#1 and then the submit button would take them to 'blah.com/recruit.php?p=form2' and so forth.
<form id="form" action="recruit.php?p=form2" method="post">
This does not work but I don't understand why. I've looked around the internet and I've found a few forum topics that discuss similar issues but none of them actually go into much detail about the solution or why this approach won't work.
Can anyone explain to me what it is I am doing wrong please? I have a feeling it is stupidly obvious but I can't put my finger on it.
Many thanks,
Splatgore
Some working sample code to do what I think you're trying to achieve:
<?php
$p = intval($_GET['p']);
if ($p == 0)
{
$p = 1; // default to first form
}
if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
{
// get / set all forms values here since subsequent forms will be
// posting the previous forms' data via hidden fields
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$tel_number = $_POST['tel_number'];
if ($p == 3)
{
// all forms done, insert to MySQL here
}
if ($p == 2)
{
// form 2's validation
$p = 3; // set so that the form that follows will now show the
// third form
}
if ($p == 1)
{
// form 1's validation
$p = 2; // set so that the form that follows will now show the
// second form
}
}
?>
<form id="form" action="recruit.php?p=<?php echo $p; ?>" method="post">
<h2>Form #<?php echo $p; ?></h2>
<?php
if ($p == 1)
{
?>
<!-- form 1's fields // -->
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name" size="40" value="<?php echo $first_name; ?>" /></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name" size="40" value="<?php echo $last_name; ?>" /></p>
<?php
}
if ($p == 2)
{
?>
<!-- form 2's fields // -->
<p><label for="tel_number">Tel Number:</label>
<input type="text" name="tel_number" id="tel_number" size="25" value="<?php echo $tel_number; ?>" /></p>
<p><input type="hidden" name="first_name" value="<?php echo $first_name; ?>" />
<input type="hidden" name="last_name" value="<?php echo $last_name; ?>" /></p>
<?php
}
if ($p == 3)
{
?>
<!-- form 3's fields // -->
<div>
<input type="hidden" name="first_name" value="<?php echo $first_name; ?>" />
<input type="hidden" name="last_name" value="<?php echo $last_name; ?>" />
<input type="hidden" name="tel_number" value="<?php echo $tel_number; ?>" />
</div>
<?php
}
?>
<p><input type="submit" value="Submit"></p>
</form>
It looks somehow you have nested forms.
This is not possible in HTML.
If you are going with your approach, just use always the same submit button which leads to the same php script.
In the php script check which hidden fields are already set to see how far the process is.
A better approach IMO would be tough to store the data in a session var and always lead to another form page.

Categories