echo a function value won't pass on a form - php

----UPDATE: trying to find a different solution here, please take a look -------
I am trying to post a form with hidden values on a shop platform with payment gateway to receive the values.
The value name "Order_Total" uses php echo called "$sum" to display the sum to pay like this:
<Input type="hidden" name="sum" value="<?php echo $order_total; ?>">
$sum is a function which reads the user order id amount
$order_total = left_to_pay_for_order($oid);
the function works like this:
function left_to_pay_for_order($oid)
{
global $wpdb;
$s = "select * from ".$wpdb->prefix."order_contents where orderid='$oid' and paid='0'";
$r = $wpdb->get_results($s);
$total = 0;
if(count($r) > 0)
{
foreach ($r as $row)
{
$total += $row->price * $row->quant;
$shp = get_post_meta($row->pid, 'shipping', true)* $row->quant;
$total += $shp;
}
}
return $total;
}
The Payment gateway receives all other values except the $order_total value.
UPDATE !!! --------------------------------
The value passed as '0' - Any thoughts on that can happen ?
I have tested and the function works prior to sending the form and redirect, the sum display according to expected result on any HTML prior to sending, but the form send value "0".
what am I doing wrong? have searched everywhere. your kind help is very much appreciated.
Thanks !!
As per request here is the whole Form page Code - modified per StackOverflow:
<?php
global $wp_query, $wpdb, $current_user;
get_currentuserinfo();
$uid = $current_user->ID;
$user_email = $current_user->user_email;
$business = get_option('Theme_tranzilla_ID');
if(empty($business)) die('ERROR. Please input your tranzilla ID.');
//-------------------------------------------------------------------------
$oid = $_GET['oid'];
$order_total = Theme_left_to_pay_for_order($oid);
$title_post = sprintf(__('Order Payment ID #: %s','Walleto'), $oid);
//---------------------------------
$tm = current_time('timestamp',0);
$cancel_url = get_bloginfo("siteurl");
$response_url = get_bloginfo('siteurl').'/?w_action=tranzila_order_response';
$ccnt_url = Theme_my_account_link();
$currency = get_option('Theme_currency');
?>
<html>
<head><title>Processing Tranzilla Payment...</title></head>
<body onLoad="document.form_mb.submit();">
<center><h3><?php _e('Please wait, your order is being processed...', 'Theme'); ?></h3></center>
<FORM name="form_mb" Action='https://direct.tranzila.com/Terminal_Name/' method='POST'>
<Input type="hidden" name="supplier" value="<?php echo get_option('Theme_tranzilla_ID') ?>">
<Input type="hidden" name="sum" value="<?php echo $order_total; ?>">
<Input type="hidden" name="currency" value="1">
<input type="hidden" name="email" value="<?php echo $user_email; ?>">
</FORM>
</body>
</html>

Please, tell us what you see in a "inspect".. what the value in the input before post.
But.. with information that you give, I think:
1) You are missing a ; in the end of "echo $order_total" line. Put a ; in the end.
2) It can be some wordpress conflict with the "sum" field name. Try to change to "order_total".

Related

How to deal with unchecked checkbox array value without javascripts?

Suppose I have a form like this, where checkboxes are repeating fields:
<form action="" method="post">
<?php for($i=0; $i<3; $i++) { ?>
<input type="checkbox" name="ch[]" value="1">
<?php } ?>
<button type="submit" name="submit">submit</button>
</form>
I'm on WordPress and using custom meta boxes for dealing with it. So I declared the form within the callback function of the metabox, and receiving the values in another save function that's hooked with save_post and new_to_publish action hooks.
So what's happening: when I click on the button, the metabox callback submitted the form, and the hooked function receives it. (Can be visible at add_meta_box() WordPress Codex) Suppose my save function contains:
<?php
if( isset($_POST['submit']) ) {
$chb = $_POST['ch'];
$result = array();
foreach ($chb as $cb) {
$result[] = array( 'isactive' => $cb );
}
var_dump($result);
}
?>
It's showing that, checkboxes are not returning any value when unchecked. I considered all the server-side solutions mentioned here: Post the checkboxes that are unchecked
PROBLEM is, whenever the form is submitted, it's taking the checkboxes' values to an array(), so I can't check the array values like:
if( !isset( $_POST['ch'] ) || empty( $_POST['ch'] ) ) {
$chb = 0;
} else {
$chb = 1;
}
I also tried hidden field with 0 value, accompanied with array_unique(), but nothing seems work for me.
How can I deal with unchecked checkboxes in an array so that they can't be null, and my foreach can loop through all of 'em and store data accordingly, and correct?
I want to avoid JavaScripts solutions.
If you name the checkboxes with an index in them, like so:
<input type="checkbox" name="chk_<?php echo $i ?>" value="1">
Then you could loop through them like so:
<?php
$chkBoxes = array();
foreach ($_POST as $k => $v) {
if (strpos("chk_",$k) === 0) {
$cbIndex = str_replace('chk_', '', $k);
$chkBoxes[$cbIndex] = $v;
}
}
Then to test if a checkbox was checked and sent to the server, you could use:
<?php
if (isset($chkBoxes[$cbIndex]))
Remember - the value of the checkbox is only sent if it was checked: Does <input type="checkbox" /> only post data if it's checked?
Add a hidden field in the form with the number of checkboxes, and use the index $i for the array ch[]:
<form action="" method="post">
<input type="hidden" name="num" value="<?= $num = 3 ?>">
<?php for($i=0; $i<$num; $i++) { ?>
<input type="checkbox" name="ch[<?= $i ?>]" value="1">
<?php } ?>
<button type="submit" name="submit">submit</button>
</form>
Then:
<?php
if( isset($_POST['submit']) ) {
$chb = $_POST['ch'];
$num = $_POST['num'];
$result = array();
for($i=0; $i<$num; $i++) {
$result[$i]['isactive'] = isset($chb[$i]) ? 1 : 0;
}
var_dump($result);
}
?>
first of all i copied ideas from many people inside this forum! i only synthesized the way!
my function to get data from my base located inside the $anoigmata class:
function getall() {
$data = $this->_db->get('<table_name>', array('ID', '>=', 0));
$results = $data->results();
$rows = $data->count();
return array($results, $rows);
}
code inside the create function to save all the secondary options that are not presented on the site.
$fields_Κ = array('history' => serialize(array(
'checkboxes' => Input::get('checkboxes')
)),
);
$data = $this->_db->insert('ΚΕΛΥΦΟΣ', $fields_Κ);
return true;
the php-html code that shows the result
<form method="post">
<div class="form-group">
<label for="checkboxes[]">checkboxes title</label><br>
`<?php
for ($i=0; $i<$anoigmata->getall()[1]; $i++) {
echo "
<input type='hidden' name='checkboxes[$i]' value='0' />
<input type='checkbox' id='checkboxes[$i]' name='checkboxes[$i]' value='".$anoigmata->getall()[0][$i]->ΕΜΒΑΔΟΝ."' />".$anoigmata->getall()[0][$i]->ΠΕΡΙΓΡΑΦΗ."<br>";}?>`
`</div><button type="submit" class="btn btn-success">Submit</button></form>`
***ΕΜΒΑΔΟΝ and ΠΕΡΙΓΡΑΦΗ are the row names from my table that i'm saving!!!
i hope i helped a little..!

Avoid losing POST data when using php pagination

I am working on a renting website that transfer date from page to another, for example the user enter a date and some information and when he goes to another page he should find the information that he entered in the first page. Everything works fine except that when I add pagination like this: [1] [2] [3] [4] every time I click on a page number in the pagination the POST data will be lost. For example if I clicked number 2 in the pagination I get this message:
Undefined index: date......
I found some solutions which is using get method but I don't know how to use get method in this situation.
What should I change to my code to avoid losing POST data?
here is my full code:
<?php
$date= $_POST['date']; // the post data from previous page
$info= $_POST['info']; // the post data from previous page
?>
<form action="next_page.php" method="post" name="myForm">
<input name="date" type="hidden" value="<?php echo $date; ?>" />
<input name="info" type="hidden" value="<?php echo $info; ?>" />
<?php
include(db.php);
$q="select count(*) \"total\" from users";
$ros1=mysql_query($q,$link);
$row=(mysql_fetch_array($ros1));
$total=$row['total'];
$dis=8;
$total_page=ceil($total/$dis);
$page_cur=(isset($_GET['page']))?$_GET['page']:1;
$k=($page_cur-1)*$dis;
$query="SELECT * FROM cars limit $k,$dis";
$ros=mysql_query($query,$link);
while($row = mysql_fetch_array($ros))
{
echo $row["user_id"];
echo $row["user_name"];
echo $row["user_email"];
}
for($i=1;$i<=$total_page;$i++){
if($page_cur==$i){
echo ' <input type="button" value="'.$i.'"> ';
}
else{
echo ' <input type="button" value="'.$i.'"> ';
}}
?>
<input type="submit" name="userId" value="' .$row['user_id'] . '" />
</form>
You should use GET method instead of POST method.
<?php
$date = $_GET['date']; // the post data from previous page
$info = $_GET['info']; // the post data from previous page
?>
<form action="next_page.php" method="get" name="myForm">
<input name="date" type="hidden" value="<?php echo $date; ?>" />
<input name="info" type="hidden" value="<?php echo $info; ?>" />
<?php
include(db . php);
$q = "select count(*) \"total\" from users";
$ros1 = mysql_query($q, $link);
$row = (mysql_fetch_array($ros1));
$total = $row['total'];
$dis = 8;
$total_page = ceil($total / $dis);
$page_cur = (isset($_GET['page'])) ? $_GET['page'] : 1;
$k = ($page_cur - 1) * $dis;
$query = "SELECT * FROM cars limit $k,$dis";
$ros = mysql_query($query, $link);
while ($row = mysql_fetch_array($ros)) {
echo $row["user_id"];
echo $row["user_name"];
echo $row["user_email"];
}
for ($i = 1; $i <= $total_page; $i++) {
if ($page_cur == $i) {
echo ' <input type="button" value="' . $i . '"> ';
} else {
echo ' $i ';
}
}
?>
<input type="submit" name="userId" value="' .$row['user_id'] . '" />
</form>
You can use PHP sessions to store users input on the server:
PHP Sessions
Keep all the data in $_SESSION and read it from there when it's needed in the page.
Update the stored values when the users inputs something new.
You should store this information somewhere between your http-requests. There are some possible solutions for that:
you can store this information in the database
in session (temporarily store, if you don't need this data in your database)
store in every html page as a hidden field
A good way in my opinion is to start the seach with a POST form and if the results exceed a limit then construct pagination links which really are post forms incorporating the search keyword and target page in the form of hidden variables.
Passing the search keyword as a get parameter needs care (url encode) because urls have limits on the characters they allow (ascii letters and digits, and characters such as /, ~, -, _ etc ) for example a user might search for something in japanese or greek or use symbols.
Passing the search keyword as a session variable also needs care. Consider this scenario: a user has opened multiple result pages, but all pages will hereafter have access to the last processed session saved keyword. Also storing the search keyword in a session requires coordination by the developer such as when to destroy the session variable etc.

Setting variable and string from POST with loop

Currently I have 100 text input boxes named contact0 through contact101. I am trying to get the Post data and name each string to itself. Meaning $contact0 = $_POST['contact0'];all the way up to $contact101 = $_POST['contact101']; there has to be a simpler way to set them in a loop or something. Overall the end result is I just want the data entered in the textbox to become the value of the textbox when submitted. Any suggestions will help I might be doing this wrong for the results I want.
for ($i = 0; ;$i++){
if($i < 101){
$contact.$i = $_POST['contact'].$i;
echo $contact.$i;
}
else{
break;
}
}
for ($i = 0; $i <= 101; $i++){
${"contact".$i} = $_POST['contact'.$i];
echo ${"contact".$i};
}
You may want to consider amending your HTML form. Rather than create 100 new variables, you can assign all the contacts to an array and then reference them with the array index.
HTML
<input type="text" name="contacts[]" value="Contact 1 name"/>
<input type="text" name="contacts[]" value="Contact 2 name"/>
// etc...
PHP
$contacts = $_POST['contacts'];
var_dump($contacts);
// prints array(0 => 'Contact 1 Name', 1 => 'Contact 2 Name'...
As it now an array, you can reference the contact e.g. $contacts[34] and know it will be a valid entry.
EDIT
A working example:
<?php
if (isset($_POST['contacts'])) {
$contacts = $_POST['contacts'];
echo "<p>The contacts are below:</p>";
print_r($contacts);
} else {
echo "<p>Please enter the contacts</p>";
}
?>
<form method="post" action="">
<?php for($x = 0; $x < 100; $x++): ?>
<input type="text" name="contacts[]" value="<?php echo (isset($contacts[$x])) ? $contacts[0] : ''; ?>"/>
<?php endfor; ?>
<input type="submit" name="submit" value="submit"/>
</form>
Edit 2
I have now made the form a loop, meaning it will create all our contact inputs for us. On top of this, if we have already posted the form each field will have the correct contact values.
If you are not aware of the syntax, echo isset($contacts[$x])) ? $contacts[$x] : ''; is a ternary operator which is a one line if/else statement.
Which can also be tested here: http://phpfiddle.org/api/run/ugb-cta

Send dynamic array in form via $_POST to html email

This title might not describe my question too well but I was unsure how to name this post... Anyways, I have a form that has dynamically generated input boxes that pulls the last 4 years with the following:
<?php
$current_date = new DateTime();
for ($i = 1; $i <= 4; $i++) {
$current_date->modify('-1 year');
$date_string = $current_date->format('Y')
?>
<fieldset name="gross_sales">
<input type="number" name="year_brand_gross[<?php echo $date_string; ?>]" placeholder="Gross Sales for <?php echo $date_string; ?>">
</fieldset>
<?php
} // end while
?>
And once the user clicks submit the form data is processed via my process.php file that contains the following:
$year_brand_gross[1] = $_POST['year_brand_gross'][1];
$year_brand_gross[2] = $_POST['year_brand_gross'][2];
$year_brand_gross[3] = $_POST['year_brand_gross'][3];
$year_brand_gross[4] = $_POST['year_brand_gross'][4];
Now I'm pretty sure the above part is not right. So this is my question... How would I get the info from these inputs into my email that's sent since their created by an array and not "actually" there. Here's a stripped down version of my html email that's sent which I'm pretty sure is also wrong since the above code is incorrect:
<table>
<tr>
<td>Gross Sales:</td>
</tr>
<tr>
<td>{$year_brand_gross[1]}</td>
<td>{$year_brand_gross[2]}</td>
<td>{$year_brand_gross[3]}</td>
<td>{$year_brand_gross[4]}</td>
</tr>
</table>
Any help is greatly appreciated!
Your form would actually look like
<input type="number" name="year_brand_gross[2012]" ... />
<input type="number" name="year_brand_gross[2011]" ... />
<input type="number" name="year_brand_gross[2010]" ... />
etc...
That means you need to use
$_POST['year_brand_gross'][2012]
$_POST['year_brand_gross'][2011]
$_POST['year_brand_gross'][2010]
etc...
on the server.
foreach($_POST['year_brand_gross'] AS $yeah => $value) {
// use $year and $value variables to do whatever
// this code will execute once for each values in $_POST['year_brand_gross'].
// note: print_r($_POST);
// $_POST is an array, same for $_GET and so on
}

PHP form design best practice

I have been using PHP for a while now and I have always wondered how to represent a single form to handle updates and inserts into a database. At the present, I am using 2 seperate forms to do this and they both have basically the same information and textboxes, etc. I know there is a better way of handling this but I'm not sure what that is.
I have tried to use a single form in the past but the html mixed with the php looks terrible and is really hard to maintain. I am after "clean" and neat.
Can someone please put me on the right track.
One of the things that I have to use are POST values if the user submits the form and the validation didn't pass, the refresh should not wipe out the already entered values.
You could use a single form, with a hidden field for id. If this field is set - then you should update the $_POST['id'] record with the rest of the form. If the field is not set (that is, it has value=""), you should insert the form data to a new record.
You'll set the id field according to the action, for example /data/edit/1 will set the id field to , and/data/new` will not set value to it.
For example, your view could be
<form action="/data/edit/1">
<input type="hidden" value="<?php echo $data->id; ?>" />
<input type="text" value="<?php echo $data->name; ?>" />
</form>
In case of a new record, call your view with the following data
$data->id = '';
$data->name = '';
In case of a known record, simply init the $data object with the data
$data->id = $record_id;
$data->name = $record_name;
This is how I would probably do it without using any other frameworks/libraries etc. It is basically what Elazar Leibovich said.
<?php
//id is zero or a record id depending on whether updating or inserting
//an existing record could be edited using edit.php?id=10
//if the id GET parameter is omitted a new record will be created
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
$error = '';
if ($id) {
//this array would be in the same format as the one below
$record = fetchRecordFromDb($id);
} else {
$record = array( 'field1' => 'default value', 'field2' => 'some other default' );
}
//allow POST data to override what is already in the form
foreach ($record as $key => $value) {
if (isset($_POST[$key])) {
$record[$key] = $_POST[$key];
}
}
if (isset($_POST['submit'])) {
if (!validateForm()) {
$error = 'Some form error';
} else {
if ($id) {
updateRecord($id, $record);
} else {
insertRecord($record);
}
//ok, redirect somewhere else
header('Location: http://somewhere');
exit();
}
}
?>
<form method="post">
<?php echo $error; ?>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($record['field1']); ?>"><br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($record['field2']); ?>"><br />
<input type="submit" name="submit">
</form>

Categories