I am trying to multiply to fields together to obtain a total in PHP form.
<label for="190_mnth2"></label>
<div align="center">
<input name="190_mnth" type="text" id="190_mnth2" value="10" size="5" />
</div></td>
<td><div align="center">
<label for="190_rate"></label>
<input name="190_rate" type="text" id="190_rate" value="190.00" size="10" />
</div></td>
<td><div align="center">
<input name="total_190" type="text" id="total_190" value=<? echo '190_mnth2' * '190_rate' ?> size="10" />
The above is my current code but the answer is totally wrong it gives me 36100 What is wrong with my formula if anyone can assist?
First of all you cannot calculate the total like that, it's not Javascript, you need a form with a get/post request which will send a request to the server, server will process and throw the calculated value back to the user.. so wrap the fields around forms, set your method to post(preferred) and than you can write your PHP code like
<?php
if(isset($_POST['submit_button_name'])) { //Use $_GET if it's a GET request
//Save the values in variable
$mnth_190 = $_POST['190_mnth'];
$rate_190 = $_POST['190_rate'];
//Calculate here
$total = $mnth_190 * $rate_190;
/* Now you can use $total either to echo straight in your page,
or inside another input field */
}
?>
Also make sure you validate the data before the form is posted and is calculated, check whether the user input doesn't have string or any other special character.
The purpose of PHP is to generate HTML to display, not to update the HTML of the current page. You can create a POST request that submits your data for display on another page. If you want to dynamically update the total on the current page, you should use Javascript or another front end language.
<? echo '190_mnth2' * '190_rate' ?>
You're attempting to multiply two strings, which will probably be converted by PHP as 190 * 190.
In order to get this to work, you're going to have to do it in two separate steps (with PHP anyway). Because PHP is a server side language, you'll have to $_POST[''], or submit these two values as part of the query string and use $_GET[''] to calculate.
If you don't want to do it this way, then I'd suggest looking at some JavaScript to handle it instead.
I'm going to take a shot at doing something like this, as an example.
$190_mnth2 = 10;
$190_rate = 190;
$total = $190_mnth2 * $190_rate;
then using: value=<? echo '$total'; ?>
Related
I'm sorry for my English.
I have a dynamic php form connected to mysql DB. In stock array I save the mysql query results. I can access the name of the product[0] and its available quantity [4]. I use the name of the product[0] to set input name and available quantity to fix max parameter value, as it below:
<input type="number" name="<?php echo $stock[$i][0]?>" min="0" max="<?php echo $stock[$i][4]; ?>" value="0" style="width:4em>
I don't kwow how many inputs will be created (and which, because it is dynamic), so I save the name of the input created in another array $_SESSION["INPUTS"] as show:
array_push($_SESSION["inputs"],$stock[$i][0]);
In the next page, I want to $REQUEST the value from the inputs. Now I have the problem, I need to call $REQUEST for the created inputs which names are saved inside $_SESSION["inputs"], I need something as:` $REQUEST["$_SESSION["inputs"]]. I try it different ways without exit.
Any idea? Any alternative?
thanks
I think the best approach is by naming the input name attribute like an array: eg: "name=stock[the product name]". This approach allows you to discard the usage of the $_SESSION["inputs"].
<input type="number" name="stock[<?php echo $stock[$i][0];?>]" min="0" max="<?php echo $stock[$i][4]; ?>" value="0" style="width:4em">
Then to read the values:
$stocks = $_REQUEST['stock'];
foreach($stocks as $productName => $quantity) {
//...
}
This works because the inputs are converted to a php array after being submitted.
You can even get the number of inputs by calling count:
echo count($_REQUEST['stock']);
Transfer value to another page was successful, I have read many topics on this subject, stockoverflow really helped me with this.
On the first page (eg page1.php) I have input. Normally I type a value to it.
With php I write in a session variable and after clicking submit I can transfer this value to the other side (eg page2.php) which is a simple contact page. This value is pasted into a textarea field.
My problem is that it takes only the value that I type directly to the input, which is located in page1.php. I wanted to create rather calculator, which will consist of the price according to the entered number of kilograms of product. (the kilogram is the value entered in the input).
How do I get a form field was clean, and the Order the product was all redirected correctly?
My code in page1.php :
<?php
session_start();
$_SESSION['towar1'] = $cena1;
?>
<form method="get" action="kontakt.php">
<input id="wart1" type="number" value="0" name="towar1" class="ilosc" required>
</form>
My code in page2.php(conttact page) :
<?php
session_start();
$cena1 = $_GET['towar1'];
?>
<label for="wiadomosc"></label>
<textarea placeholder="" name="wiadomosc" required><?php echo $cena1 ?></textarea>
///PROBLEM
when I trying to figure how to get good value of product price (e.g. for 1 kg will be 19$)
i wrote code of this kind directly on my page2.php:
<?php echo $cena1*19 ?>
But when I do this, any direct entrance on the contact page gives me already written text which is 0 (zero).
Can I avoid that 0? How can I make textarea will be blank always, and my page1.php (calculator) will calculate correct number (const which is 19$ per kilo and number of kilos that you entered in input)
Your question is quite not clear, lets go through this: page1.php contains input that manage Item quantity and $_SESSION variable with its price, on the page 2 you need to display quantity*price_per_item number, right? If yes, try the following approach:
<?php
session_start();
$cena1 = $_GET['towar1'] * $_SESSION['towar1'];
?>
<label for="wiadomosc"></label>
<textarea placeholder="" name="wiadomosc" required><?php echo $cena1 ?></textarea>
, where $_GET['towar1'] is an items quantity and $_SESSION['towar1'] is an item price.
p.s For more adnvanced technique do not hesitate to ask in comments.
Hope it helps, cheers.
EDIT
Considering our converstation in comments I can assume that this approach would helps you:
$cena1 = (!empty($_GET['towar1']) && $_GET['towar1'] != 0 )? $_GET['towar1'] * 19 : '';
This line check if $_GET['towar1'] variable is not empty and not zero. If it match the condition - make calculation, else - return an empty string (not zero).
Please note that everything we're talking about above is not secure and can be abused by end-user. Please consider to review input validation aproach.
The reason why it doesn't work is that you are using sessions wrong.
The workflow of application should be like:
user enters the amount
you process it, if needed you give an error message or something else
save amount to session
redirect user to next page
calculate price
display result
Code example using your code:
Page1 should be:
<?php
session_start();
if(isset($_GET['wart1'])) {
$_SESSION['towar1'] = (int) $_GET['wart1'];
header('Location: page2.php');
}
?>
<form method="get" action="kontakt.php">
<input id="wart1" type="number" value="0" name="towar1" class="ilosc" required>
</form>
Page2:
<?php
session_start();
$cena1 = $_SESSION['wart1'] * 19;
?>
<label for="wiadomosc"></label>
<textarea placeholder="" name="wiadomosc" required><?php echo $cena1 ?></textarea>
I'm new to PHP, I started about 3 weeks ago.
I have a string, which is used with $_POST to pass it to another page, the second page uses $_GET to get these url and split it as desired.
My problem is that, in my first page I use a String, and I want to encrypt it, so that I can pass it as a plan text. In the second page I must decrypt it and get it as an array.
So is there any encryption method or function I can use which is compatible with $_POST ( so I can send it to another page ) and decrypt it as an array ?
I need this method, because the second page is actually connecting to website and is a payment method. So i don't want users to manually edit the url and lower the amount of $ for the product they get.
tnx for your help.
You're thinking about this wrong. You NEVER trust information coming from the user's side.
For example, if your user sends a form that says what item they want, DO NOT include the price in the form. Instead, get the price from the server (database), where it can be trusted.
What you probably want to do is pass the contents of the users cart (i.e. the items he'd like to order) to the payment site.
Therefore, you should create a form like:
<form action="URL/to/paymentPage.php" method="post">
<!-- Item 1 -->
<input type="hidden" name="items[0]" value="productID1"/>
<input type="hidden" name="quantity[0]" value="quantity1"/>
<!-- Item 2 -->
<input type="hidden" name="items[1]" value="productID2"/>
<input type="hidden" name="quantity[1]" value="quantity2"/>
<!-- ... -->
<!-- Item n -->
<input type="hidden" name="items[n]" value="productIDn"/>
<input type="hidden" name="quantity[n]" value="quantityn"/>
<input type="submit" value="Order"/>
</form>
On the server in the file "URL/to/paymentPage.php" you can access the items using the following code:
<?php
$items = $_POST['items']; // Array of items ..
$quantities = $_POST['quantity']; // The array of quantities for each item ..
// Calculate the total price ..
$totalPrice = 0;
foreach($items as $idx => $itemID) {
if($quantities[$idx]>0) {
totalPrice += getPriceFromDB($itemID) * $quantities[$idx];
}
}
echo 'Total Price to pay: '.$totalPrice;
?>
where the function getPriceFromDB actually retrieves the price for the item/product with the id $itemID from your database or elsewhere... :)
However, the user items are usually stored in the session, and, therefore, there is no need to submit the again.. ;)
Despite not fully understanding what you're trying to achieve, you can use base64 encoding:
$encoded_string = base64_encode ($string);
$decoded_string = base64_decode ($encoded_string);
Is it possible to use php to compute something and use jquery to fetch the computed
value and display it back to the webpage without the need to submit the form.
I'm really having trouble using client-side to compute something that is using arrays. So I'm thinking of letting php do the computation.
<input type="hidden" name=ids[] value="<?php $id; ?>">
<input type="hidden" name=qoh[] value="<?php $qtyhand; ?>">
<input type="hidden" name=dprice[] value="<?php $dsprice; ?>">
<input type="hidden" name=sprice[] value="<?php $ssprice; ?>">
<td>$qtyhand</td>";
<td><input type="text" name=qbuys[] value="<?php echo $ssprice; ?>"></td>
<td><?php $ssprice; ?></td>";
<td><input type="text" name=disc[] value=""></td>
<td><input type="text" name=subtot[] value=""></td>
And here is the php file that is supposed to be used for computing.
<?php
$ctbill=0;
foreach ($_GET['ids'] as $k => $v) {
$id = (int)$v;
$qtyhnd = (int)$_GET['qoh'][$k];
$qtytbuy = (int)$_GET['qbuys'][$k];
$left = $qtyhnd - $qtytbuy;
$sellprice=(double)$_GET['sprice'][$k];
$dealerprice=(double)$_GET['dprice'][$k];
$finalvalue=.01;
$dis=(double)$_GET['disc'][$k];
$stotal=(double)$qtytbuy * $sellprice;
$cdizval=(double)$stotal * $dis * $finalvalue;
$cdstotal=$stotal-$cdizval;
$ctbill=(double)$ctbill + $cdstotal;
$dizval=$dis * $finalvalue;
$preprof=(($sellprice * $qtytbuy)-($dealerprice*$qtytbuy)) * $dizval;
$profit=(($sellprice * $qtytbuy)-($dealerprice*$qtytbuy)) - $preprof;
?>
Can you give me an idea on how to do it.
The loading itself is often as simple as
$("#output").load("compute.php?ids[]=1111&ids[]=2222");
The complexity in your case is assembling the various URL parameters from the form fields. Usually you can pass a simple Javascript array/hash as data parameter. But JS arrays and the default jQuery .load handler don't work well with repetetive PHP-style var[] field names that you have.
Your best bet is to build a loop and do that manually I think. (But there might be plugins for that, so try Google and jQuery plugin repository.)
Yes. Look at the jquery manual for examples of how to make ajax requests and show their results:
http://api.jquery.com/jQuery.ajax/
Use ajax and set those values in the callback.
jQuery's ajax functions include $.get, $.post, $.load, $.ajax . You should probably pass your parameters with POST bc it seems you want to pass some arrays and GET is not well suited for that. That PHP file should echo out the stuff you need, and depending on its complexity you may want it to be JSON used JSONencode instead of just a plain string.
$.post('/url.php', {data1: 'literal', data2: variable, ....}, function($x){--display==});
url.php is the PHP file that handles it
second argument is encoming data
third argument is a callback function, with $x being whatever url.php echos
http://api.jquery.com/category/ajax/
http://www.visualjquery.com
I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed