PHP - Php Form Math Help
Hello Everyone, I'm a newbie trying to improve my script below. The script works fine but I would like to add the 3 radio buttons computations enhancements Ergo, if a user chooses 'Matte Paper" a 10% would be added to the Price Quote result. If a user chooses ' Gloss Paper, a 10% would be added to the Price Quote result. If a user chooses 'Canvas" , a 20 % would be added to the Price Quote result. If someone could assist with the math or post me a helpful link it would be greatly appreciated. Thank you. Paul from Melbourne, Australia. <div style="border:dashed 1px; width:570px;"> <form method="post" action="<?php echo $_SERVER['php_SELF'];?>"> <p> 1. Enter the size (100w.x180h. cm) you want your picture printed: Width <input type="text" name="width" size="1" maxlength="3" value="0" onFocus="this.value=''; this.style.color='#ff0000';"> Height <input type="text" name="height" size="1" value="0" maxlength="3" value="0" onFocus="this.value=''; this.style.color='#ff0000';"> </p> <p> 2. Choose the printing material for your pictu <input type="radio" value="cms in Matte paper" name="material" size="3" maxlength="3" /> Matte Paper <input type="radio" value="cms in Gloss Paper:" name="material" size="3" maxlength="3" /> Gloss Paper <input type="radio" value="cms in Canvas:" name="material" size="3" maxlength="3" /> Canvas </p> <p> 3. Submit your info for our Price Quote below : <input type="submit" name="submit" value="Submit" /> or: <input type="submit" name="clear" value="Reset" /> </p> <p> 5. Our Price Quote to print your artwork sized: <?php $width = $_POST['width']; /* if artwork wider than 101 cm no quote, exits*/ if ($width >=101) {echo "Error!"; exit ;} $height = $_POST['height']; /* if artwork higher than 181 cm no quote, script exits */ if ($height >=181) {echo "Error!"; exit ;} $measurement = $_POST['measurement']; $material = $_POST['material']; $result = $width * $height; echo " $width x $height $material is: "; echo "$".number_format($result,2). "" ; ?> </p> </form> </div> Similar TutorialsHi, im trying to have a math captcha in my registration form, but having trouble with setting it up in my form. sorry for the large code. If i change the value of $_POST['Submit'] to something else like $_POST['Submit1'] and then same for the math image captcha then it works, but i would like it to work as part of the form, makes sense? lol right now the form just posts the value and doesnt check for captcha values! if someone could help me out here that would be great! thank you. Code: [Select] <?php if(isset($_POST['Submit'])){ if($_POST['Submit'] != $_SESSION['security_number']) { $error = ""; } else { $error = ""; } //NEED TO CHECK IF FIELDS ARE FILLED IN if( empty($_POST['name']) && (empty($_POST['email']))){ header("Location:Messages.php?msg=3"); exit(); } if( empty($_POST['pw1']) && (empty($_POST['pw2']))){ header( "Location:Messages.php?msg=4" ); exit(); } $name=$_POST['name']; $email=$_POST['email']; $pw1=$_POST['pw1']; $pw2=$_POST['pw2']; if("$pw1" !== "$pw2" ){ header( "Location:Messages.php?msg=5" ); exit(); } $ip = $_SERVER['REMOTE_ADDR']; //connect to the db server , check if uname exist include('config.php'); $query1=("Select * from user where email='$email'"); $result1= mysql_query($query1); $num1=mysql_num_rows($result1); if ($num1 > 0) {//Email already been used header( "Location:Messages.php?msg=11" ); exit(); }else{ $query=("Select * from user where uname='$name'"); $result= mysql_query($query); $num=mysql_num_rows($result); if ($num > 0) {//Username already exist header( "Location:Messages.php?msg=6" ); exit(); }else{ //if username does not exist insert user details $query=( "INSERT INTO user (uname, pw,email,date_joined,ip,level) VALUES ('$name',md5('$pw1'),'$email',NOW(),'$ip','Normal')"); if (@mysql_query ($query)) { header("location:login.php?reg=1"); exit; } } } mysql_close(); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><!-- InstanceBegin template="/Templates/Auth.dwt.php" codeOutsideHTMLIsLocked="false" --> <head> <!-- InstanceBeginEditable name="doctitle" --> <title>Registration</title> <!-- InstanceEndEditable --> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <!-- InstanceBeginEditable name="head" --> <!-- InstanceEndEditable --> <link href="styleLog.css" rel="stylesheet" type="text/css"> <script language="javascript" type="text/javascript"> function reloadCaptcha() { document.getElementById('captcha').src = document.getElementById('captcha').src+ '?' +new Date(); } </script> </head> <body> <table width="100%" border="0" cellspacing="7" cellpadding="0"> <tr class="temptitle"> <td><!-- InstanceBeginEditable name="EditRegion4" -->New User Registration <!-- InstanceEndEditable --></td> </tr> <tr> <td><!-- InstanceBeginEditable name="EditRegion3" --> <form name="form1" action="register.php" method="post"> <table width="657" border="0"> <tr> <td width="122"><div align="left">Name</div></td> <td width="525"><input name="name" type="text" size="40"></td> </tr> <tr> <td><div align="left">Email</div></td> <td><input name="email" type="text" size="40"></td> </tr> <tr> <td><div align="left">Password</div></td> <td><input name="pw1" type="password" size="40"></td> </tr> <tr> <td ><div align="left">Confirm Password </div></td> <td><input name="pw2" type="password" size="40"></td> </tr> <tr> <td><img src="math_captcha/image.php" alt="Click to reload image" title="Click to reload image" id="captcha" onclick="javascript:reloadCaptcha()" /></td> <td><input type="text" name="Submit" value="what's the result?" onclick="this.value=''" /></td> <td> </tr> <tr> <td></td> <td> <input name="Submit" type="submit" value="Register"></td> </tr> </table> </form> <?=$error?> MOD EDIT: code tags added. Basically this is a pretty straight forward application. The values are all best on a set of conditional statements held in a function and when the user presses submit, it SHOULD calculate the form....However, this is not the case, for some reason it keeps returning 0. I have tried and tried and tried....to no avail. I have attached the files so you can sort through a little easier as there are a good amount of lines. Thanks! [attachment deleted by admin] Hi, I am TheMeq. I am currently developing a Text-Based MMORPG in PHP/MySQL. I have quite alot of the code laid down, its just this bit that is starting to throw me a bit. I've been working on it since 8am this morning.. it is now 4:30pm and i think it's nearly there. It's just not working the way I would like. So if I was to ask for help, should I just post what code I have? I'm trying to make a script to check a files date time and if its under so many seconds long the page will refresh. here is what I've got. I've been testing the output of the date() functions but when i do the math all i get is a 0. where did i go wrong? is it just i can't do math with dates? Thanks in advanced. Code: [Select] <html><head> <meta http-Equiv="Cache-Control" Content="no-cache"> <meta http-Equiv="Pragma" Content="no-cache"> <meta http-Equiv="Expires" Content="0"> <? $proFile = "profilePics/profile.jpg"; //if ( date ("m d Y H:i:s.") - date ("m d Y H:i:s.", filemtime($proFile)) <= 00 00 0000 00:00:04 ){ //this is where the magic should happen. //echo "<meta http-equiv="refresh" content='4'>"; } ?> </head> <? echo date ("m d Y H:i:s."); echo "<br>"; echo date ("m d Y H:i:s.", filemtime($proFile)); echo "<br>"; echo date ("m d Y H:i:s.") - date ("m d Y H:i:s.", filemtime($proFile)); //only outputs 0 ?> I am trying to create a math equation inside a variable but I am struggling to achieve the desired result. On one php page I have this:
$x = "date('Y')"; On my main page I have linked to the above and also $description but the result I am getting is: In this classic lecture which was delivered over date('Y') - 1989 years ago,
I want to create a variable so I don't need to go back every year and change the description. Is this possible? Robert
is there a math function that give you an integer value when u divide 2 numbers? ie in 7/3 i just want 2 as a result not floating number. thanks in advance. Trying to get the percentage of rent for a property in php. Im completely lost .... Code: [Select] <?php $purchase = 44000; $rent = 9860; $percent = $purchase * $rent; //this is wrong, it returns 4.3 but should be over 18 echo "Percentage is {$percent}%"; ?> Hi guys. I'm using php to randomly generate a simple math verification question. But, I'm having a hard time validating the input. Can someone please tell me what I'm doing wrong? Thank you } else if(trim($verify) != $_SESSION['UserData']['Math'][0]+$_SESSION['UserData']['Math'][1]){ $error = '<div class="error_message">Attention! The verification number you entered is incorrect.</div>'; } <?php echo "<span class='label'><span class='required'>*</span>What is ".$_SESSION['UserData']['Math'][0]." + ".$_SESSION['UserData']['Math'][1]."?</span> "; ?> <input name="verify" type="text" id="verify" size="3" value="<?=$verify;?>" /><br /><br /> I can' t even get the simple str_replace to work. I got.... $rslt = $client->getTodaySubIDStats($key, $sub_id); $rslt = str_replace("EARNINGS",'',$rslt); $rslt = str_replace("Array","",$rslt); $rslt = str_replace("\r","",$rslt); $rslt = str_replace("\n","",$rslt); $rslt = str_replace("\t","",$rslt); print_r($rslt); which spits out.... Code: [Select] Array ( [0] => Array ( [EARNINGS] => $100.40 [CLICKS] => 1301 [LEADS] => 100 [SUB_ID] => yacker [EPC] => $0.11 ) ) I would like to have every thing removed except the '$100.40' (The number is always changing). Then remove the $ and do math 100.40*.40, so in the end, all it spits out is 40.16 and always only have two digits after the period. In a past post I mentioned that my ultimate goal of this is code is to query our SQL system for a start date and a stop date. At both of those points, the query would spit out a value for that the column based on a determined time and day. The first point would be a min or minUsage. The second point would be max or maxUsage. These points will be subtracted from each other to create a value. See below. Not that it matters but the value is the amount of kWh per months.
So, now, Min and Max are both defined below but I suspect the value is being truncated for each. Also, Im not sure the calculation is right because I am getting an unexpected solution. I am asking that someone look at this code and tell me what should be happening mathematically. (down to the accuracy of the answer (pre calculation and post calculation) It would help me better see my mistakes.
To give you an example of some data. I have
Max ( or July 31)
total_energy_a =26872
total_energy_b =27619
total_energy_c =26175
Min ( or July 1)
total_energy_a =20347
total_energy_a =20914
total_energy_a =19808
Max - Min
19597
With these numbers, would you expect this outcome from this code?
Thanks.
<?php $sql = ";WITH TOTAL_KWH_SUMMER AS ( SELECT CONVERT(VARCHAR(10),cdate,111)AS trans_date, datepart(hh, cdate) as trans_hour, comm_id, MIN((total_energy_a+total_energy_b+total_energy_c)/100) AS minUsage, MAX((total_energy_a+total_energy_b+total_energy_c)/100) as maxUsage, repeated FROM [radiogates].[dbo].[purge_data] where comm_id='$comm_id' group by comm_id, CONVERT(VARCHAR(10),cdate,111), datepart(hh, cdate), repeated ) SELECT *, datepart(weekday, trans_date) as trans_date_day, datepart(month, trans_date) as trans_date_month, maxUsage - minUsage as totalUsage FROM TOTAL_KWH_SUMMER where datepart(weekday, trans_date) IN ('1', '2', '3', '4', '5', '6', '7') AND DATEPART(MONTH, trans_date) IN ('5','6','7','8','9','10') and trans_date BETWEEN '$startdate2 00:00:01' AND '$enddate2 24:00:00' and repeated <> '1' "; $query = sqlsrv_query($conn, $sql);if ($query === false){ exit("<pre>".print_r(sqlsrv_errors(), true));}while ($row = sqlsrv_fetch_array($query)){ $sumUsageKWH += $row[totalUsage];}sqlsrv_free_stmt($query);?> Website: http://novacms.vacau.com/index.php I'm trying to make a calculator for this game I play, it's fully developed, but with one bug. It doesn't do the math right. $goal = The amount of EXP (Experience Points) someone wants to get $exp = The amount of EXP they currently have $npcs_exp["exp"] = The amount of EXP the monster has But, when they enter in the information, the calculation is all screwed up. When I do it, it seems to give me the same number EACH time. The part where the calculation "goes down". Remember, I'm trying to see how many times you need to kill a NPC to achieve your goal. //math $npc_exp_extract = mysql_query("SELECT exp FROM npcs WHERE name='$npc'"); $npcs_exp = mysql_fetch_assoc($npc_exp_extract); $amount = $goal / $npcs_exp["exp"]; Full code: <?php $exp = $_POST["exp"]; $npc = $_POST["npc"]; $goal = $_POST["goal"]; mysql_connect("removed", "removed", "removed"); mysql_select_db("a2248602_npcs"); if(!$goal || !$npc || !$exp) { echo "<center><form action='index.php' method='POST'>GOAL: <input type='text' name='goal'> Current XP: <input type='text' name='exp'>"; echo "NPC: <select name='npc'>"; $npc_extract = mysql_query("SELECT * FROM npcs"); while($npcs = mysql_fetch_assoc($npc_extract)) { echo "<option name='". $npcs['name'] ."'>". $npcs['name'] ."</option>"; } echo "</select> <input type='submit'></form></center>"; } else { //math $npc_exp_extract = mysql_query("SELECT exp FROM npcs WHERE name='$npc'"); $npcs_exp = mysql_fetch_assoc($npc_exp_extract); $amount = $goal / $npcs_exp["exp"]; if($amount=="1") { echo "You will need to kill a <b/>". $npc ."</b> <b>". $amount ."</b> more time. You earn ". $npcs_exp["exp"] ." XP for each kill from this NPC. | <a href='index.php'>Do another</a><br/><br/>"; } else { echo "You will need to kill a <b/>". $npc ."</b> <b>". $amount ."</b> more times. You earn ". $npcs_exp["exp"] ." XP for each kill from this NPC. | <a href='index.php'>Do another</a><br/><br/>"; } } echo "<center>Made by Zaros from <a href='creation-x.net'>Creation-X</a></center>"; ?> Mod edit: DB credentials removed. Hey.
So imagine this example...
class FormulaEvaluator { ...... //Construct & variables here.. public function exec() { //Missing some lines here, but you get the idea $formula = $this->formula; $context = (array) $this; ob_start(); $res = eval('return ' . $formula . ';'); } } $formulaEvaluator = new FormulaEvaluator(); $formula = '10 * (($Test * 2) + ($Test2 / 3))'; $formulaEvaluator->formula = $formula; $formulaEvaluator->Test = 20000; $formulaEvaluator->Test2 = 300000; $res = $formulaEvaluator->exec(); echo $res; //1400000The code we have is working as intended, but we want to avoid using eval. I know it's a pretty common question, and the answer is usually the same, but is there any way to do something similar without using eval? Please deal with me for a moment as I try to explain what is occurring. I have created drop down menu that you choose a name and the php/MySQL will run multiple queries to display information regarding the chosen name. The query works great. There is no problem with the query. However when you leave the page, either by navigation or by X'ing out. When you return there are two errors that pop up: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in You can then use the drop down menu and choose a name and it all works great. It is my belief that these errors occur due to how the query was written, as the two queries that have these errors both have math in them. My question is, how do I block these errors from occurring when you return to the page? Here is the query: <?php //Worst Regular Season Record include_once('../other/functions.php'); $con = mysql_connect($hostname, $username, $password) OR DIE ('Unable to connect to database! Please try again later.'); $db = mysql_select_db($dbname, $con); $query = "SELECT win, loss, year, teamname FROM standings, owners WHERE owners.owner_id = standings.owner_id AND win = (SELECT MIN(win) FROM standings) AND standings.owner_id = $thing ORDER BY year"; $result = mysql_query($query); $row = mysql_fetch_array($result); @ mysql_data_seek($result, 0); if(mysql_num_rows($result)>0) { echo "<table CELLPADDING=5 border =1>"; echo "<tr>"; echo "<th align=center colspan=4 > Worst Regular Season Record </th>"; echo "</tr>"; while ($row = mysql_fetch_array($result)) { echo "<tr>"; echo '<td align=center> In '.$row['year'].', the '.$row['teamname'].' had '.$row['win'].' wins, and '.$row['loss'].' losses.</td>'; echo "</tr>"; } } else { } echo "</table>"; mysql_close($con); ?> What is the correct way to right a simple maths question i have my total as: <?php echo $row['total'];?> i have my another number as: <?php echo $row['user_credit']; ?> but what i want to do is subtract the user_credit from the total and save it as a new variable called 'credits_used' but im unsure how to write it do i do it like $row['total'] - $row['user_credit'] = $row['credit_used']; Thank for any help I can not seem to figure out how to do this.. I just need to add 100+99+98+97+96...+1 no you can not do 100! because that multiples them =] Good day, I have problem on subtracting time. Can anyone give me a hint how will I going to do that.
I already manage to get the SUM on time addition using this method.
$data = array('1:52:37','9:56:39','08:04:22','05:32:20'); echo convertTime($data); - ANSWER 25:25:58 function convertTime($data){ $seconds = null; $minutes = null; $hours = null; foreach($data as $key => $value){ $time1 = explode(':',$value); list($h[$key],$m[$key],$s[$key]) = $time1; $seconds += $s[$key]; $minutes += $m[$key]; $hours += $h[$key]; } $total_sec_min = intval($seconds / 60); $total_seconds = $seconds % 60; #$total_seconds; $total_minutes = $minutes % 60; if($total_sec_min > 0){ $total_minutes = $total_minutes + $total_sec_min; } $total_min_hr = intval($minutes / 60); $total_hours = $hours; if($total_min_hr > 0){ $total_hours = $total_hours + $total_min_hr; } return $total_hours.':'.sprintf("%02s",$total_minutes).':'.sprintf("%02s",$total_seconds); }But I really got hard time when it comes to subtraction. This topic has been moved to PHP Math Help. http://www.phpfreaks.com/forums/index.php?topic=350528.0 Having to go into somebody else's code yet again! Gah! Originally the totaling page just subtracted a flat discount. But now the client wants to be able to subtract percentage discounts and 'per item' discounts. In the discount table I added a field to determine whether the discount chosen is to be applied as flat off total, flat per item, % off total, and % off each item. I also entered a field that can have a class id, in case this discount is only for that class. (the intention being that otherwise the discount is on anything) I've got a session variable that generates something like : Array ( [217] => 1 [215] => 2 ) meaning 1 person in class #217, and 2 people in class 215. $_SESSION['s_to_be_added'] = array_filter($_POST['participantqty']); Then on the page I'm concerned with, I've been trying to write the script. I know I still need some math stuff figured out But how do I take the array, do the math, and then generate an overall cost for the whole thing? and this is just the discounting? I don't even have a clue how to work in delimiting it if there's a class id.. did any of that make sense? Code: [Select] <?php // the above is the array I want to use to $passed_array = array_filter($_SESSION['s_to_be_added']); // this is the discount 'code' the user entered. $discount = mysql_escape_string($_POST['discount']); // just a donation added after everything. $donation = mysql_escape_string($_POST['donation']); // finding the discount that matches the discount 'code' entered. $query_selectAllItems_events = "SELECT discount_amount,discount_type,workshop_link_1 FROM tbl_discount where discount_value = '$discount'"; $result_all_events = mysql_query($query_selectAllItems_events); $numRows_all_events = mysql_num_rows($result_all_events); $num=mysql_num_rows($result_all_events); $z_row = mysql_fetch_array($result_all_events); // this is just a number: 1, 20, 90 etc. $discount_amount = $z_row['discount_amount']; /*this is 1,2,3,4 - for each type of discount 1- flat 2- flat per item 3- discount on all, 4- discount per item */ $discount_type = $z_row['discount_type']; // the workshop id if the discount is onlyh for this workshop $discount_link_1 = $z_row['workshop_link_1']; // just a description $discount_name = $z_row['discount_name']; if ($discount_type ==1) { /* flat discount on total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total - $discount_amount); $final_total = ($final_total + $donation); } elseif ($discount_type ==2)) { /* discount per item total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total - $discount_amount); $final_total = ($final_total + $donation); } elseif ($discount_type ==3)) { /* percentage discount on total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total * ($discount_amount/100)); $final_total = ($final_total + $donation); } elseif ($discount_type ==4)) { /* percentage discount per item here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total * ($discount_amount/100)); $final_total = ($final_total + $donation); } ?> Hi guys! Am trying to get hold of a PHP Math Expression Parser that follows correct precedence and executes custom functions. Can somebody share his scripts? or lead me to the right directions? Hope you can help! Thanks a lot! My boss is gonna kill me soon. This is 1 week overdue already. Jon My code is $answer = (1/212500); output is 4.90205690308E-6 while I need I output as 0.00000470588 Please help, and tell me what is the specific problem, |