PHP - Field Calculation Formula
Hi,
I need field calculation formula. I have following four fields. I want to calculate End Date based on values in Tracking Unit, Total Units and Start Date. Tracking Unit (Daily,Weekly,Monthly,Quarterly) for example Tracking Unit => Monthly Total Units => 12 Start Date => 2011-01-01 End Date => 2011-12-01 another example Tracking Unit => Weekly Total Units => 12 Start Date => 2011-01-01 End Date => ? I want to calculate End Date either in PHP or Javascript. Any idea? Similar TutorialsOk so I basically have two textfields and a submit button. The first text field basically allows the user to input a duration of an event in the format of Hours:Minutes:Seconds such as: 02:30:00 is two and a half hours. The second textfield allows the user to put in an average time 'something' does something in the same format as above. So for example 00:20:00 is 20 minutes. 1st Textfield: Code: [Select] <input name="tmarrtextfield" type="text" class="textbox" id="tmarrtextfield" value="00:00:00"> 2nd Textfield: Code: [Select] <input name="tmatttextfield" type="text" class="textbox" id="tmatttextfield" value="00:00:00"> What I need is for when the form is submitted to the same page.. the code to...: 1. Convert the normal text info into actual time data. 2. Divide the duration by the average timing so for example: 02:30:00 (150 minutes) / 00:20:00 (20 minutes) = 7.5 (Would return a rounded down number or up, doesn't matter) then store the number as a variable that will be echoed later. Harry. This code, that I didn't write, but am trying to modify, generates the cost of a video purchase. One line (line 32) is a formula , I believe for setting a purchase price amount: $amout += $video->video_play_price?$video->video_play_price:$video_cost; Another line (line 50) is a formula for deducting to create another amount: $uploader_amount = $video_cost - $charge; I think line 50 is correct except for I don't think $video_cost in the final price, but I'm no expert at reading this code. I tried this without success: $uploader_amount = $video_play_price - $charge;
Here is the full code, any help with line 50, will be appreciated. <?php if (IS_LOGGED == false) { $data = array('status' => 400, 'error' => 'Not logged in'); echo json_encode($data); exit(); } if (!empty($_POST['id'])) { if (!is_array($_POST['id'])) { $id_array[] = $_POST['id']; } else { $id_array = $_POST['id']; } // get cost video $db->where('name', 'video_play_price'); $db_cost = $db->getOne('config'); $video_cost = (float)$db_cost->value; $count_video = count($id_array); $user_id = $user->id; $wallet = (float)str_replace(',', '', $user->wallet); $amout = 0; foreach ($id_array as $id) { $video_id = (int)PT_Secure($id); // get video data $video = $db->where('id', $id)->getOne(T_VIDEOS); $amout += $video->video_play_price?$video->video_play_price:$video_cost; } // $amout = $video_cost * $count_video; $charge = ( $video_cost *0.50 ); if ($wallet >= $amout) { $new_wallet = (string)($wallet - $amout); $db->startTransaction(); $inserted_records = 0; foreach ($id_array as $id) { $video_id = (int)PT_Secure($id); $uploader_amount = $video_cost - $charge; // get video data $video = $db->where('id', $id)->getOne(T_VIDEOS); // add data to paid table $insert_buy = $db->insert('u_paid_videos', [ 'id_user' => $user_id, 'id_video' => $video_id, 'session_key' => $_SESSION['session_key'], 'video_play_price' => (string)$video_cost, 'video_title' => $video->title, 'user_id_uploaded' => $video->user_id, //'up_credit'=>$video_cost, 'up_credit'=>$uploader_amount, ]); if ($insert_buy) { $inserted_records++; } //add wallet users' video $userwallet = $db->where('id', $video->user_id)->getOne(T_USERS); //$videouserwallet = $userwallet->wallet+$video_cost; $videouserwallet = $userwallet->wallet+$uploader_amount; $db->where('id', $video->user_id); $update_wallet = $db->update(T_USERS, [ // 'wallet' => $videouserwallet, 'wallet' => number_format($videouserwallet, 2, '.', ''), ]); } $db->where('id', $user_id); $update_wallet = $db->update(T_USERS, [ 'wallet' => $new_wallet, ]); if (($inserted_records == $count_video) && $update_wallet) { $db->commit(); echo json_encode([ 'status' => 200 ]); exit(); } else { $db->rollback(); echo json_encode([ 'status' => 400, 'error' => 'Buy process error' ]); exit(); } } else { echo json_encode([ 'status' => 400, 'error_num' => 1, 'error' => 'Not enough money' ]); exit(); } } else { echo json_encode([ 'status' => 400, 'error' => 'Bad Request, Invalid or missing parameter' ]); exit(); }
Hello all. Trying this again. I would like to implement a simple math formula based on a date, but not sure how to do that exactly. I run a sports league, and want to calculate fees based upon a fixed date. Prior to 'some date' use this calculation, but after this date, add late fees using 2nd calculation. In my code there are two fields: $earlyteam and $lateteam. I need $lateteam to kick in after 'some date'. Help? Code: [Select] //calculate Fees $size = $lSize['size']; switch($size) { case 2: $base = 150; $size = 3; break; case 4: $base = 330; $size = 6; break; case 6: $base = 550; $size = 10; break; default: die ("invalid league size"); }; $earlyTeam = $base; { $e_each = $earlyTeam / $pCount; $lateTeam = $earlyTeam * 1.10; $l_each = $lateTeam / $pCount; } I am trying to write a script for a puzzle based on the user's IP address, but I just can't wrap my head around how to do it. Essentially, when the visitor loads the page two things happen: (1) a PHP application returns an image to serve as a background for the formula, (2) implement the algorithm of generating the formula based on IP, that is displayed on the image.
The puzzle itself would be in the form of ABC.DEF.GHI.JKL where each letter would be associated with the corresponding digit in their IP addy. The user is trying to solve for partial map coordinates. So, let's say the correct answer is N 35 54.374 W 084 01.829 and the user's IP is 075.036.025.058. The formula returned and placed on the image would be N 35 54. (E) (B) (F - H) W 084 01. (L) (H) (B + H) Whatever I use as the final correct answer will not change and be the same for all users; only the puzzle formula would differ for each user as it would be based on their IP at the moment. Any help here would be greatly appreciated. Thanks! Gary This is my first real jump into PHP, I created a small script a few years ago but have not touched it since (or any other programming for that matter), so I'm not sure how to start this. I need a script that I can run once a day through cron and take the date from one table/filed and insert it into a different table/field, converting the human readable date to a Unix date. Table Name: Ads Field: endtime_value (human readable date) to Table Name: Node Field: auto_expire (Converted to Unix time) Both use a field named "nid" as the key field, so the fields should match each nid field from one table to the next. Following a tutorial I have been able to insert into a field certain data, but I don't know how to do it so the nid's match and how to convert the human readable date to Unix time. Thanks in advance!. Hi: I'm going crazy trying to do the following: I'm making a job registration process where the user registers on one php page to the website, must acknowlege and email receipt using an activate php page, then is directed to upload their C.V. (resume) based on the email address they enter in the active page output. I then run an upload page to store the resume in teh MySQL db based on the users email address in the same record. If I isolate the process of the user registering to the db, it works perfectly. If I isolate the file upload process into the db, it works perfect. I simply cannot upload teh file to the existing record based on teh email form field matching the user_email field in the db. With the processes together, teh user is activated, but teh file is not uploaded. Maybe I've simply been at this too long today, but am compeled to get through it by end day. If anyone can help sugest a better way or help me fix this, I will soo greatly appreciate it. My code is as follows for the 2 pages. ---------activate.php------- <?php session_start(); include ('reg_dbc.php'); if (!isset($_GET['usr']) && !isset($_GET['code']) ) { $msg = "ERROR: The code does not match.."; exit(); } $rsCode = mysql_query("SELECT activation_code from subscribers where user_email='$_GET[usr]'") or die(mysql_error()); list($acode) = mysql_fetch_array($rsCode); if ($_GET['code'] == $acode) { mysql_query("update subscribers set user_activated=1 where user_email='$_GET[usr]'") or die(mysql_error()); echo "<h3><center>Thank You! This is step 2 of 3. </h3>Your email is confirmed. Please upload your C.V. now to complete step 3.</center>"; } else { echo "ERROR: Incorrect activation code... not valid"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Job application activation</title> </head> <body> <center> <br/><br/><br/> <p align="center"> <form name="form1" method="post" action="upload.php" style="padding:5px;"> <p>Re-enter you Email : <input name="email" type="text" id="email"/></p></form> <form enctype="multipart/form-data" action="upload.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="4000000"> Upload your C.V.: <input name="userfile" type="file" id="userfile"> <input name="upload" type="submit" id="upload" value="Upload your C.V."/></form> </p> </center> </body> </html> --------upload.php---------- <?php session_start(); if (!isset($_GET['usr']) && !isset($_GET['code']) ) { $msg = "ERROR: The code does not match.."; exit(); } if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $email = $_POST['email']['user_email']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } include 'reg_dbc.php'; $query = "UPDATE subscribers WHERE $email = user_email (name, size, type, content ) ". "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; mysql_query($query) or die('Error, query failed'); mysql_close($dbname); } ?> <center> <br/> <br/> <br/> <br/> Thank you for uploading your <?php echo "$fileName"; ?> file, completing your registration, and providing us your C.V. for this position. <br/> <br/> <br/> We will contact you if your canditature qualifies. </center> Dear All, I am trying to fetch the sum of a column for current date and subtract a value from the sum for currently selected record. The query i build works fine in MySql but when the same query i placed in php no result it's blank. Below is the query.
<?php //Calculation for no of paxs. $query2=mysqli_query($con,"SELECT SUM(noopaxs-gattl) FROM tblsupvisitor where date(EnterDate) = CURDATE() || gst = 'INH' || gst = 'IN' GROUP BY confno"); $calc_no_paxs_for_today=mysqli_fetch_row($query2); $gattl=$calc_no_paxs_for_today['gattl']; ?>
and her is the assignment to the textbox.
<div class="row form-group"> <div class="col col-md-3"> <label for="textarea-input" style="color: purple" class=" form-control-label"><strong>Total No. Of Adults</strong></label> </div> <div class="col-12 col-md-9"> <input name="gattl" id="gattl" rows="9" class="form-control" required="" value="<?php echo $gattl;?>"> </div> </div>
Any help in this regard will be highly appreciated.
Kind Regards, Naveed. This is a bit of a puzzle. Look at the sum and result below: Code: [Select] $markTotal += ($session['Mark'] / 100 * $session['SessionWeight']); Result on Browser Module: CHI2550 - Modern Database Applications 41.2 (this is $markTotal) Session: AAB 72(this is $session['Mark']) 20% (this is $session['SessionWeight']) (The percentage signs are just add ons) Session: AAE 67(this is $session['Mark']) 40% (this is $session['SessionWeight']) As you can see the answer to the calculation above is right, the answer is 41 .2 as it adds up the two session marks, divide by 100 and then times it by the total amount of the percentage. But I want to include a total mark where except it is out of the total session percentage (60% for above example), it is out of a 100% but I can not work as simple as that as in above example one session is worth more than other. I have worked out that the answer for the total mark of the above example out of 100% should be 69, but how do I achieve this in my calculation. Thank you and any help is much appreciated So how Hi, I have a calculation issue in my php. Below is my code: $ Code: [Select] moduletotal = 0; $modulecount = 0; $sessionweight = 0; while ($row = mysql_fetch_array($result)){ $moduletotal += $row['Mark']; $modulemark = (int)($moduletotal); // Here and above is the calculation which is simply adding the total number of marks // Below is the code that displays my results. The variable of the calculation is shown at the end of the last if statement (3rd one down) $output = ""; $studentId = false; $courseId = false; $moduleId = false; if($studentId != $row['StudentUsername']) { $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})"; } if($courseId != $row['CourseId']) { $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <br><strong>Year:</strong> {$row['Year']}</p>"; } if($moduleId != $row['ModuleId']) { $moduleId = $row['ModuleId']; $output .= "<p><br><strong>Module:</strong> {$row['ModuleId']} - {$row['ModuleName']} {$row['Credits']} $modulemark</p>"; } $output .= "<p><strong>Session:</strong> {$row['SessionId']} {$row['Mark']} {$row['Grade']} {$row['SessionWeight']}%</p>"; } echo $output; ?>The Results look like this at the moment (The answer the calculation is next to each Module): Student: Mayur Patel (u0867587) Course: INFO101 - Bsc Information Communication Technology Year: 3 Module: CHI2550 - Modern Database Applications 20 72 (72 is the answer to the calculation for the first module but this is incorrect at it should also add the 67 and thus become 139) Session: AAB 72 A 20% Session: AAE 67 B 40% Module: CHI2513 - Systems Strategy 20 200 (200 is the answer to the calculation for this module but this is incorrect it should be only 61. But what it has done is that it has added the 72 and 67 from the first module and added it with the 61 in this module) Session: AAD 61 B 50% SO WHAT MY QUESTION IS HOW CAN I GET THE CALCULATION SO THAT IT ONLY ADDS UP EACH SESSION MARKS THAT BELONGS TO A MODULE ONLY? IN THE EXAMPLE ABOVE IT SHOULD ONLY ADD THE MARKS FOR SESSION AAB AND AAE IN THE MODERN DATABASE APPLICATIONS MODULE AND THEN WHEN IT GETS TO THE NEXT MODULE WHICH IS SYSTEMS STRATEGY, THE MARKS FOR THAT MODULE SHOULD START AGAIN AND ADD ON THE MARKS FOR THE SESSION AAD IN THAT MODULE. HOPEFULLY YOU UNDERSTAND AND THANK YOU Below is the query if you want to look at it: Code: [Select] $query = " SELECT c.CourseName, st.CourseId, st.Year, st.StudentUsername, st.StudentForename, st.StudentSurname, s.ModuleId, s.SessionId, s.SessionWeight, gr.Mark, gr.Grade m.ModuleName, m.Credits, FROM Course c INNER JOIN Student st ON c.CourseId = st.CourseId JOIN Grade_Report gr ON st.StudentId = gr.StudentId JOIN Session s ON gr.SessionId = s.SessionId JOIN Module m ON s.ModuleId = m.ModuleId WHERE (st.StudentUsername = '".mysql_real_escape_string($studentid)."') ORDER BY c.CourseName, st.StudentUsername, m.ModuleName, s.SessionId "; Hi, I have an itinerary form at http://www.happydaysremovals.com/estimate.html Customers fill this in, and it uses phpmailer-fe to email the results to myself. I use a HTML .tpl file so I can make the output email look as I want. All that is fine, but I would like a volume calculator. Next to each item on the form, the customer enters the amount of that item, usually 1 or 2. If it was say a setee, I want to define that a setee = 30 cubic feet, for example. Then I want the calculator to calculate the total cubic footage for all the variables, and include it in the html email. I know with javascript this can be done, but I was hoping for a PHP result and for it to somehow work in with phpmailer-fe, for example: </style> <script language="JavaScript"> function write_this() { var setteelarge; var setteemedium; var setteesmall; var setteelarge2; var setteemedium2; var setteesmall2; var setteelargeresult; var setteemediumresult; var setteesmallresult; var total; setteelarge = document.form1.LargeSettee.value; setteemedium = document.form1.MediumSettee.value; setteesmall = document.form1.SmallSettee.value; setteelarge2 = 45 setteemedium2 = 31 setteesmall2 = 22 setteelargeresult = (setteelarge * setteelarge2); setteemediumresult = (setteemedium * setteemedium2); setteesmallresult = (setteesmall * setteesmall2); total = (setteelargeresult+setteemediumresult+setteesmallresult) document.form1.Total_Cubic_Feet.value = total } </script> Basically, I want to be able to include the cubic feet total value to also be emailed to me in the HTML email, but preferably all in PHP. At the moment, I get everyones itinerary, but want to be automatically be able to work out the cubic footage. Thanks Code: [Select] $new_array2=array_diff($my_array,$itemIds); $updatedb = mysql_query("UPDATE content_type_ads SET field_expire_value = '666' WHERE $new_array2 = field_item_id_value"); "$new_array2" has only 12 digit numbers for each item in the array, and I want to match them to the "field_item_id_value" field in the table, updating the "field_expire_value" field for the record where they match. I know I am close because the UPDATE code works before I add the WHERE statement (it of course adds '666' to EVERY field, but for a noobie it's a start!). (Another quite newbie...) I have already an online booking form. The Form works fine now and I would like to add on one more issue, but the code ignores what I want to check. I have 4 fields: arrival, departure, no. of persons and comments to check. Scenario 1: All field mentioned above are emtpty: Workes fine and message appears: "You have not provided any booking details". Scenario 2: If arrival (date_start) and departure (date_end) is entered, there should be at least an entry either in the field "comment", or in the field "pax". If not, there should be a message: "You have not provided sufficient booking details". INSTEAD: The booking request is sent, which should not be the case. The code is currently: # all fields empty : arrival, departure, pax and comments - error if(empty($data_start) && empty($data_end) && empty($pax)&& empty($comment)){ exit("You have not specified any booking details to submit to us. <br>Please use your browser to go back to the form. <br>If you experience problems with this Form, please e-mail us"); exit; } #If arrival and departure date is entered, there should be at least an entry either in the field "comment", or in the field "pax". if(!isset($data_start) && !isset($data_end) && empty($pax) && empty($comment)){ exit("You have not provided sufficient booking details. <br>Please use your browser to go back to the form. <br>If you experience problems with this Form, please e-mail us"); exit; } The form can be tested at http://www.phuket-beachvillas.com/contact-own/contact-it.php Can someone please check and tell me what's wrong with the code ? Thanks to anyone for any hint. This is a bit of a puzzle. Look at the sum and result below: Code: [Select] $markTotal += ($session['Mark'] / 100 * $session['SessionWeight']); Result on Browser with explanation to help you: Module: CHI2550 - Modern Database Applications 35% (this is $markTotal) ... This is where I want add the total mark for 100% Session: AAB 100% (this is $session['Mark']) 10% (this is $session['SessionWeight']) Session: AAE 50% (this is $session['Mark']) 50% (this is $session['SessionWeight']) All percentage marks above are just add ons. As you can see the answer to the calculation above is right, the answer is 35 as it adds up the two session marks, divide by 100 and then times it by the total amount of the percentage. But I want to include a total mark where except it is out of the total session percentage (60% for above example as one Session is 40% and the other is 20%), it is out of a 100% but I can not work as simple as that as in above example one session is worth more than other. The total mark out of 100% of the above example should be 65%, but how do I achieve this in my calculation. It is not as simple as dividing the $session['Mark'] because one session is worth more than the other. So the above example will have 2 marks: one mark out of total percentage of the Sessions which for the above example is 35% and second mark is out of the full 100% of the module which is 65%. Thank you and any help is much appreciated The time dosen't calculate correctly!!! When the local time is 3:15pm on16th Nov 2010 - "Time Expired" dosen't show. When I echo $drawT-time() it shows 60000 odd. What's wrong here? $drawH = 15; $drawM = 15; $drawM = 11; $drawD = 16; $drawY = 2010; $cutoffT = 4; $drawT = mktime($drawH, $drawM, 0, $drawM, $drawD, $drawY); date_default_timezone_set("Australia/Melbourne"); if($drawT-time() < $cutoffT*60) { echo "Time Expired."; } Good day! I've been stumbled into a situation wherein the user have predefined time (this will be the expiration time) and the system will have to compare the user time based on server time. I've done the job in getting the time with timezone inclusion using javascript var userDate = new Date(); // output : Tue Dec 06 2011 16:18:23 GMT+0800 (PHT) I passed that javascript value using ajax to the server, the problem I encounter is the compare the current server date with the userDate. Any solution? Thanks in advance. Hi. I am writing software to choose employees for drug testing. Originally it was choosing 5 per day, Mon-Thu. No problem there, that's easy. Now, they want to ensure everyone gets tested each calendar year. So now I need the program to look at the date and calculate the days between now and 12/31 then divide the people that haven't been tested by days to get number per day that need testing so it gets all done by the end of the year.
The snag I hit is how to calculate it. I can easily get days to 12/31, but I need to drop the Fridays, Saturdays and Sundays of each week. That has me a little perplexed. Is there a way to make that kind of calculation? Thanks!
When I use this: echo number_format(150 + 20.95 + .5, 2); ... I get 170.95. Yet on my calculator, 150 + 20.95 + .5 gives me 171.45. Why is that? Please help me calculate this according to the "if" condition. $scoreM['newtag'] + $scoreU['newPrice'] $SomeVar = 'currentPrice'; $queryU = "SELECT * FROM db1 WHERE bookprice = '".$SomeVar."'"; $resultU = mysql_query($queryU); $scoreU = mysql_fetch_assoc($resultU); echo $scoreU['newPrice']; echo $scoreU['weeklyScr']; echo $scoreU['priceX']; //// $WinVar = 'additionalAmount'; $query = "SELECT * FROM db2 WHERE booklist = '".$WinVar."'"; $result = mysql_query($query); $scoreM = mysql_fetch_assoc($result); echo $scoreM['newtag']; echo $scoreM['priceY']; if($scoreU['priceX']== $scoreM['priceY']) { $udatedValue = ($scoreM['newtag'] - $scoreU['newPrice']); echo(udatedValue); } else{ $udatedValue = ($scoreM['newtag'] + $scoreU['newPrice']); echo(udatedValue); } |