PHP - How To Insert Math Formulas In Php?
With this code, I am trying to create a guessing game. When I press the START button, I want it display a guess, highest, and the lowest number between 1-100. The highest number being 100, and the lowest being 1. I'm trying to get the math formula to do this equation (Guess = round((Highest +Lowest))/2. Can any one give me a hand.
Code: [Select] <head> <title> Project 3 </title> </head> <body> <h1>Guessing Game</h1> <form method='post' action=''> <input type='submit' name='start' id='start' value='Start Game'> <form method='post' action=''> <input type='submit' name='higher' id='higher' value='Higher'> <form method='post' action=''> <input type='submit' name='lower' id='lower' value='Lower'> <?php if (isset($_POST['start'])) { print"<input type = 'hidden' name = 'hdnCount' value = '$count'> <input type = 'hidden' name = 'hdntop' value = '$top'> <input type = 'hidden' name = 'hdnbottom' value = '$bottom'> <input type = 'hidden' name = 'hdnguess' value = '$guess'>"; } if (isset($_POST['higher'])) { $count = $_REQUEST["hdnCount"]; $top = $_REQUEST["hdntop"]; $bottom = $_REQUEST["hdnbottom"]; $guess = $_REQUEST["hdnguess"]; print" <input type = 'hidden' name = 'hdnCount' value = '$count'> <input type = 'hidden' name = 'hdntop' value = '$top'> <input type = 'hidden' name = 'hdnbottom' value = '$bottom'> <input type = 'hidden' name = 'hdnguess' value = '$guess'>"; } if (isset($_POST['lower'])) { $count = $_REQUEST["hdnCount"]; $top = $_REQUEST["hdntop"]; $bottom = $_REQUEST["hdnbottom"]; $guess = $_REQUEST["hdnguess"]; print" <input type = 'hidden' name = 'hdnCount' value = '$count'> <input type = 'hidden' name = 'hdntop' value = '$top'> <input type = 'hidden' name = 'hdnbottom' value = '$bottom'> <input type = 'hidden' name = 'hdnguess' value = '$guess'>"; } ?> </form> </body> </html> Similar TutorialsHey.
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? Hello I would like to know how to parser chemical and mathematical formulas into images or html-based layout. Please advise me. Thank you. Hi all, I've stored a formula in a mysql db table that is pretty basic. To give an example: Code: [Select] IF(x=1) { y = 2; } IF(x=2) { y = 3; } IF(x>2) { y = 0; } x represents the value from the input field from while y represents the output value (that will be shown through a span element innerHTML). My question is, how can I firstly retrieve this formula from the table and then secondly adapt the x as the value from the input field and then show the result as the output? Thanks Can anyone tell me why this is not INSERTing? My array data is coming out just fine.. I've tried everything I can think of and cannot get anything to insert.. Ahhhh! <?php $query = "SELECT RegionID, City FROM geo_cities WHERE RegionID='135'"; $results = mysqli_query($cxn, $query); $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($row = mysqli_fetch_array($results)) { $insert_city_query = "INSERT INTO all_illinois SET state_id=$row[RegionID], city_name=$row[City] WHERE id = null" or mysqli_error(); $insert = mysqli_query($cxn, $insert_city_query); if (!$insert) { echo "INSERT is NOT working!"; exit(); } echo $row['City'] . "<br />"; echo "<pre>"; echo print_r($row); echo "</pre>"; } //while ($rows = mysqli_fetch_array($results)) } //if (mysqli_num_rows($results)) else { echo "No results to get!"; } ?> Here is my all_illinois INSERT table structu CREATE TABLE IF NOT EXISTS `all_illinois` ( `state_id` varchar(255) NOT NULL, `city_name` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; Here is my source table geo_cities structu CREATE TABLE IF NOT EXISTS `1` ( `CityId` varchar(255) NOT NULL, `CountryID` varchar(255) NOT NULL, `RegionID` varchar(255) NOT NULL, `City` varchar(255) NOT NULL, `Latitude` varchar(255) NOT NULL, `Longitude` varchar(255) NOT NULL, `TimeZone` varchar(255) NOT NULL, `DmaId` varchar(255) NOT NULL, `Code` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; I'm missing something here. I have a form, and when the submit is pressed, the relevant post data inserts into table one, then I want the last insert id to insert along with other form data into a second table. The first table's still inserting fine, but I can't get that second one to do anything. It leapfrogs over the query and doesn't give an error. EDIT: I forgot to add an error: I get: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage, why VALUES ('14', '', '123', '','1234', '', '')' at line 1 query:INSERT INTO tbl_donar (donar_fname, donar_name, donar_address, donar_address2, donar_city, donar_state, donar_zip, donar_email, donar_phone, donar_fax, donar_company) VALUES ('test 14', 'asdfa', 'asdf', 'adf','asdf', '', '', '', '123', '', '') Code: [Select] if (empty($errors)) { require_once ('dbconnectionfile.php'); $query = "INSERT INTO tbl_donar (donar_fname, donar_name, donar_address, donar_address2, donar_city, donar_state, donar_zip, donar_email, donar_phone, donar_fax, donar_company) VALUES ('$description12', '$sn', '$description4', '$cne','$description5', '$description6', '$description7', '$description8', '$description9', '$description10', '$description11')"; $result = @mysql_query ($query); if ($result) { $who_donated=mysql_insert_id(); $query2 = "INSERT INTO tbl_donation (donor_id, donor_expyear, donor_cvv, donor_cardtype, donor_authorization, amount, usage, why) VALUES ('$who_donated', '$donate2', '$donate3', '$donate4','$donate5', '$donate6', '$donate7')"; $result2 = @mysql_query ($query2); if ($result2) {echo "Info was added to both tables! yay!";} echo "table one filled. Table two was not."; echo $who_donated; //header ("Location: http://www.twigzy.com/add_plant.php?var1=$plant_id"); exit(); } else { echo 'system error. No donation added'; 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}%"; ?> 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> 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'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
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? 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. 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 =] This topic has been moved to PHP Math Help. http://www.phpfreaks.com/forums/index.php?topic=350528.0 I'm using this code to get me the variables to a select box on a register page: $vars['user-birthdate-years'] = array(_VARS_USER_CHOOSE_ => "Please choose", _VARS_USER_NONE_ => _VARS_USER_UNDEF_); for ($i = date('Y') - 18; $i > date('Y') - 75; --$i) { $vars['user-birthdate-years'][$i] = "$i"; } This gives me this result in the page source: <select name="birthyear" class="date"><option value="-2" selected="selected">Please choose</option><option value="1997">1997</option><option value="1996">1996</option><option value="1995">1995</option><option value="1994">1994</option><option value="1993">1993</option><option value="1992">1992</option><option value="1991">1991</option><option value="1990">1990</option><option value="1989">1989</option><option value="1988">1988</option><option value="1987">1987</option><option value="1986">1986</option><option value="1985">1985</option><option value="1982">1982</option><option value="1981">1981</option><option value="1980">1980</option><option value="1979">1979</option><option value="1978">1978</option><option value="1977">1977</option><option value="1976">1976</option><option value="1975">1975</option><option value="1974">1974</option><option value="1973">1973</option><option value="1972">1972</option><option value="1971">1971</option><option value="1970">1970</option><option value="1969">1969</option><option value="1968">1968</option><option value="1967">1967</option><option value="1966">1966</option><option value="1965">1965</option><option value="1964">1964</option><option value="1963">1963</option><option value="1962">1962</option><option value="1961">1961</option><option value="1960">1960</option><option value="1959">1959</option><option value="1958">1958</option><option value="1957">1957</option><option value="1956">1956</option><option value="1955">1955</option><option value="1954">1954</option><option value="1953">1953</option><option value="1952">1952</option><option value="1951">1951</option><option value="1950">1950</option><option value="1949">1949</option><option value="1948">1948</option><option value="1947">1947</option><option value="1946">1946</option><option value="1945">1945</option><option value="1944">1944</option><option value="1943">1943</option><option value="1942">1942</option><option value="1941">1941</option></select> Problem: When running the php code at the top it miss two years in the span as you see in the page source below, the year 1983 and 1984 is completely missing in the page source. Why is this happening, could the php code be corrected or is there a workaround in php for the missing years bug I seem to have found? I really appreciate any help on this! Edited by Drezzzer, 12 January 2015 - 05:16 AM. 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. question here... say we have a string coming from a form, already verified that its numeric/mathmatical(+-*/) how can we then process that into an answer without using eval? Code: [Select] $string='1+2*3'; echo process($string); #7 Quote If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP 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. 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. 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, |