SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 30

Thread: PHP noob

  1. #1
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP noob

    Can you put and if statement in a variable?
    I have this code that works fine but I want to be able to call on an if statement later on down the page to get a grand total. What I am tying to do is at the bottom of the code
    PHP Code:
    while($row mysql_fetch_array($result))
      {
      echo 
    "Timecard for: <b>" $row['name'] . "</b>";
      echo 
    "<br />";    
      echo 
    "Clocked in at: " $row['time_in'];
      echo 
    "<br />";
      echo 
    "Current time: $time";
      echo 
    "<br />";
      
    $timein $row['time_in'];
    $to_time=strtotime("$time");
    $from_time=strtotime("$timein");
    $diff=round(abs($to_time $from_time) / 60);
    echo 
    "Total time: $diff minutes";
    echo 
    "<br />";
                                              
    //******Adult total********//
    echo " Total per adult: ";
     
    $adults = ($row['adults']);
     
    $intfee 12.00// $12 min. fee
     
    $minchrg .40//cents over minimum time
     
    $first 30.00//min
     
    $totaltime = ($diff 6);
     
    $over = ($totaltime $first); // min over minimum time
     
    $adultpay = ($intfee *$adults);
      if (
    $totaltime <= $first) {
        echo 
    "$$adultpay * including 6 <b><u>FREE</u></b> minutes";
          }
     
      if (
    $totaltime $first) {
     
    $overmin = ($over $minchrg $intfee);
     
    $overminadultspay = ($over $adults);
        echo 
    "$$overminadultspay * including 6 <b><u>FREE</u></b> minutes";   
          }
          
    echo 
    "<br />";
     
    $kids = ($row['kids']);
     
    $intfeekid 9.00// $12 min. fee
     
    $minchrgkid .30//cents over minimum time
     
    $firstkid 30.00//min
     
    $totaltime = ($diff 6);
     
    $over = ($totaltime $first); // min over minimum time
     
    $kidspay = ($intfeekid $kids);
                                              
    //*******kid total************//
    echo "Total per child: ";
     function 
    adulttotal() { if ($totaltime <= $firstkid) {
        echo 
    "$$kidspay * including 6 <b><u>FREE</u></b> minutes";
          }
     
      if (
    $totaltime $first) {
     
    $overmin = ($over $minchrgkid $intfee);
     
    $overminkidpay = ($overmin $kids);
        echo 
    "$$overminkidpay * including 6 <b><u>FREE</u></b> minutes";   
          }}
          
    echo 
    "<br />";
    echo 
    "Grand total: ";  // how to get the sum of adult and kid here? 
    I think that function might help but everything I have tried has not worked. any advice is greatly appreciated.
    Thanks DXM

  2. #2
    SitePoint Enthusiast
    Join Date
    Dec 2010
    Location
    Canada, Alberta
    Posts
    50
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you could create a function with parameters to return true or false or you could define a constant

    ex:

    PHP Code:
    define('IS_OK'$cnd1 $cnd2 && $cnd3 $cnd4);

    if(!
    IS_OK){
    //something

    note:code above is untested

  3. #3
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks charlestonolaes..
    I have no clue how to make a function, even after looking it up I have no clue how I would even start to make one. Mybe if I give a small example of what I am trying to do you might be able to show me a small example of the function I would need to make. when people clock out I get the total time they are clock in, if they are clocked in 36 minutes or less I want it to show them owing $12.00 and for every minute over 36 to add another 40cents to the $12.00. It is doing this for both adult and kid fees. I have it all working up to this point. at the end I want it to get the total of both. Im pretty sure a function will work I just have no clue how.
    PHP Code:
    echo " Total per adult: ";
     
    $adults = ($row['adults']);
     
    $intfee 12.00// $12 min. fee
     
    $minchrg .40//cents over minimum time
     
    $first 30.00//min
     
    $totaltime = ($diff 6);
     
    $over = ($totaltime $first); // min over minimum time
     
    $adultpay = ($intfee *$adults);
      if (
    $totaltime <= $first) {
        echo 
    "$$adultpay * including 6 <b><u>FREE</u></b> minutes";
          }
     
      if (
    $totaltime $first) {
     
    $overmin = ($over $minchrg $intfee);
     
    $overminadultspay = ($over $adults);
        echo 
    "$$overmin * including 6 <b><u>FREE</u></b> minutes";   
          }
          
    echo 
    "<br />";
     
    $kids = ($row['kids']);
     
    $intfeekid 9.00// $12 min. fee
     
    $minchrgkid .30//cents over minimum time
     
    $firstkid 30.00//min
     
    $totaltime = ($diff 6);
     
    $over = ($totaltime $first); // min over minimum time
     
    $kidspay = ($intfeekid $kids);
    echo 
    "Total per child: ";
      if (
    $totaltime <= $firstkid) {
        echo 
    "$$kidspay * including 6 <b><u>FREE</u></b> minutes";
          }
     
      if (
    $totaltime $firstkid) {
     
    $overmin = ($over $minchrgkid $intfee);
     
    $overminkidpay = ($overmin $kids);
        echo 
    "$$overmin * including 6 <b><u>FREE</u></b> minutes";   
          }

    echo 
    "<br />";
    echo 
    "Grand total: "//Have no clue at this point 

  4. #4
    SitePoint Enthusiast
    Join Date
    Dec 2010
    Location
    Canada, Alberta
    Posts
    50
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's an example I threw together real quick, I haven't tested it tho. I would strongly suggest creating a class instead of using functions for this but creating classes can be rather complicated... even I'm still learning.

    Here's a good read but rather long PHP: Classes and Objects - Manual

    PHP Code:
    function display2( array $args = array() ){
        
        global 
    $total;
        
        
    //default values
        
    $defaults = array(
            
    'type' => null,
            
    'fee' => 12.00,
            
    'min' => .40,
            
    'first' => 30.00,
            
    'diff' => null
        
    );
        
        
    //merge it with the new values
        
    $args += $defaults;
        
        
    $totaltime = ($args['diff'] - 6);
        
        
    $over = ($totaltime $args['first']);
        
        
    $pay = ( $args['fee'] * $args['type'] );
        
        
    $output '';
        
        if( 
    $totaltime <= $args['first'] ){
            
    $output .= "$$pay * including 6 <b><u>FREE</u></b> minutes";
        }
        
        if (
    $totaltime $args['first']) {
            
            
    $overmin = ($over $args['min'] + $args['fee']);
            
    $output .= "$$overmin * including 6 <b><u>FREE</u></b> minutes";
        }
        
        
    //I don't know how you calculate the total so this is just a guess
        
    $total += $pay;
        
        
    //returns the output string
        
    return $output;
        
    }

    function 
    display(){
        
        
    $output '';
        
        
    //stuff you did before
        
    $time // whatever the value is
        
        //query here
        
        
    while($row mysql_fetch_array($result)){

            
            
    $args null;
            
            
    $timein $row['time_in'];

            
    $to_time=strtotime("$time");

            
    $from_time=strtotime("$timein");

            
    $diff=round(abs($to_time $from_time) / 60);
            
            
    //$args is the paramter to passinto the function
            
    $args = array('type' => $row['adults'], 'diff' => $diff);
            
            
    //same as above
            
    $args2 = array(
                
    'type' => $row['kids'],
                
    'fee' => 9.00,
                
    'min' => .30,
                
    'diff' => $diff
            
    );
            
            
    $output .= "Timecard for: <b>" $row['name'] . "</b>";

            
    $output .= "<br />";    

            
    $output .= "Clocked in at: " $row['time_in'];

            
    $output .= "<br />";

            
    $output .= "Current time: $time";

            
    $output .= "<br />";
            
            
    $output .= "Total time: $diff minutes";

            
    $output .= "<br />";

            
    //******Adult total********//

            
    $output .= " Total per adult: ";
            
            
    $output .= display2($args);
            
            
    $output .= "<br />";
            
            
    $output .= display2($args2);
            
        }
        
        return 
    $output;
        
    }


    $total null;

    echo 
    display();

    echo 
    "<br />";
    echo 
    "Grand total: $total"//Have no clue at this point 
    essentially there two functions that just constructs the markup you need. this is typically how functions are written and used but the one I wrote here isn't exactly functional.

    It's good to break up small sections of your script into functions so that you can easily reuse them, like a function to calculate the price or a function to calculate the time. Hope this helps

  5. #5
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Try this, create a function called ;

    billableMinutes();

    which seems to want to take 2 arguments, $time_in and $time.

    Now what format are those 2 variables going to be in?

    Is $time the actual time now?

    If so we can let the function itself determine that, therefore it only needs one argument to work on.

    In that case you want the line:
    PHP Code:
    billableMinutes($row['time_in']); 
    to mean and be a placeholder for and be the equivalent of all this code:
    PHP Code:
    $timein $row['time_in']; 
    $to_time=strtotime("$time"); 
    $from_time=strtotime("$timein"); 
    $diff=round(abs($to_time $from_time) / 60); 
    Does that get you thinking about dividing up your code into at least one function? if so let us know, and we can work on it.

  6. #6
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    This may not be your exact case, but as you have not replied and I have to go out, here is one way of working out billable minutes and bundling it into a function.

    This code can be anywhere, as long as your script can include it, or if it written in your script:
    PHP Code:
    function billableMinutes$timein ){
    $to_timetime(); // time now
    $from_time=strtotime($timein); 
    $diff=round(abs($to_time $from_time) / 60);
    return 
    $diff;


    PHP Code:
    // this is pretending to be a time selected from 
    // your database
    $row['time_in']  = "2011-08-27 08:00:00";


    // then, wherever you need to work out and access
    // billable minutes without cluttering your code up
    // you just call it, you also decide wether to echo it:

    echo billableMinutes($row['time_in']);

    // or say, use it to work out hours

    $hours billableMinutes($row['time_in']) / 60 

  7. #7
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks again charlestonolaes and CUPS..
    But being so now to PHP and this being what i think is a really complex code it seems that "cups" idea might be the easier way for me to go. Would what you guys are trying to explain to me be replacing all of this
    PHP Code:
    echo " Total per adult: ";
     
    $adults = ($row['adults']);
     
    $intfee 12.00// $12 min. fee
     
    $minchrg .40//cents over minimum time
     
    $first 30.00//min
     
    $totaltime = ($diff 6);
     
    $over = ($totaltime $first); // min over minimum time
     
    $adultpay = ($intfee *$adults);
      if (
    $totaltime <= $first) {
        echo 
    "$$adultpay * including 6 <b><u>FREE</u></b> minutes";
          }
     
      if (
    $totaltime $first) {
     
    $overmin = ($over $minchrg $intfee);
     
    $overminadultspay = ($overmin $adults);
        echo 
    "$$overminadultspay * including 6 <b><u>FREE</u></b> minutes";   
          }
          
    echo 
    "<br />";
     
    $kids = ($row['kids']);
     
    $intfeekid 9.00// $12 min. fee
     
    $minchrgkid .30//cents over minimum time
     
    $firstkid 30.00//min
     
    $totaltime = ($diff 6);
     
    $over = ($totaltime $first); // min over minimum time
     
    $kidspay = ($intfeekid $kids);
    echo 
    "Total per child: ";
    $mincheck = ($totaltime <= $firstkid);
     if (
    $mincheck) {
        echo 
    "$$kidspay * including 6 <b><u>FREE</u></b> minutes";
          }
     
    $overcheck = ($totaltime $firstkid);
      if (
    $overcheck) {
     
    $overmin = ($over $minchrgkid $intfeekid);
     
    $overminkidpay = ($overmin $kids);
        echo 
    "$$overminkidpay * including 6 <b><u>FREE</u></b> minutes";   
          }
           
    echo 
    "<br />";
    echo 
    "Grand total: "
    with the new format or would this function be under the grand total part only. I tried to pretty much start from scratch on a new file with the function being the main part but got discourage and trashed it. I still have what I posted above and am going to start on a new file trying to make it function. Was I heading in the right direction when I tried to make it all one function? Or would it be a function to figure adult fee and one for a kids fee.

    Maybe the whole system could be better and this might help you help me. When a person clocks in on the main form they enter their name, a PIN (twice), how many people over 17, and how many kids 16 and under then submit the form. Now when they enter the name and PIN in the clock out form it uses the time stamp from the submitted "clock in form" and the the php time stamp when they hit clock out. So the time in is from the database and clock out is the current time(not from db). I suppose I don't need it to but I wanted it to show the total per adult and per kid then on the grand total to multiply by the number of adult's and kid's and add together.

  8. #8
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    You would likely have several discrete functions, which for now you can keep at the top of this script.

    Each function should just do one very simple thing, and by virtue of its name should be absolutely very obvious what it does.

    To extract these functions you leave your script as it is - then copy the bit of code you want to work on to another file and get that working as you expect.

    That was what I was illustrating in the code I posted for you - even though I am guessing what the values passed to it are going to be.

    When you have your function working in its own little file you can then reintroduce to your main script.

    As I said at the top of this reply, you can just paste it at the top of the file for now.
    PHP Code:
    <?php

    function billableMinutes$timein ){
    $to_timetime(); // time now
    $from_time=strtotime($timein); 
    $diff=round(abs($to_time $from_time) / 60);
    return 
    $diff;
    }


    // here have the rest of your script;

    echo " Total per adult: "
     
    $adults = ($row['adults']); 
     
    $intfee 12.00// $12 min. fee 
     
    $minchrg .40//cents over minimum time 
     
    $first 30.00//min 
    // and so on
    If your PHP editor or IDE features "code folding" you can roll that function up, and essentially hide it from view.

    In time the next step is that you would put all these functions into a single file lets call it booking_functions.php and simply include it on those scripts which need access to one or more of those functions.

    As I said you want small, discrete specialised pieces of code that you might want to use again on this site, or even on other sites on the same server.

    Then something magical happens because you :
    a) build up a library of useful functions
    b) you start to separate concerns
    c) you promote code re-use
    d) your code becomes easier to read and maintain..

    So, that is the big picture.

    Focussing on what you said now, putting the whole script into one function is a waste of time. You would probably only ever use that script in one place, on this page - that is a waste of time.

    So, do not despair that you cannot make it go into one function.

    Tell me what is the exact value you have in $row['time_in'] - don't describe it, paste the value here - and now I ask you this question again;

    Is $time the actual time now?
    Lets get billableMinutes() working in an isolated file, then I will show you how to add that into your code.

    Then we can move on and see if we can extract another function from that code.

  9. #9
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks CUPS..

    my $row['time_in'] when I call it is: 2011-08-28 16:47:20
    I would rather just have it as hour, minute and seconds but im not sure how to go about that

    and $time is the real time now

    I have started the function on a new file this is what I have now
    PHP Code:
    <?php
     
     
    // Connects to your Database 

     
    mysql_connect("localhost""root""********") or die(mysql_error()); 

     
    mysql_select_db("timelog") or die(mysql_error()); 
     
     
     
    date_default_timezone_set ("America/Denver");
    $time date"Y-m-d H:i:s"time()); //time right now


     // now retrives db entry
    date_default_timezone_set ("America/Denver"); $time date"Y-m-d H:i:s"time());
     
         
    $result mysql_query("SELECT * FROM log
    WHERE name LIKE 'Zach999' and pin LIKE '1234'"
    );
     

    while(
    $row mysql_fetch_array($result))
      {
      
    $time date"Y-m-d H:i:s"time());
      
    $timein = ($row['time_in']);
      
    $to_timedate"Y-m-d H:i:s"time()); //Time now
      
      
    function billableMinutes$timein ){
        
    $to_time$to_time=strtotime("$time"); //Time now
        
    $from_time=strtotime($timein);
        
    $diff=round(abs($to_time $from_time) / 60);
        return 
    $diff;
        }
        echo 
    billableMinutes$timein );
        echo 
    "<br />";
        echo 
    $to_time;
        echo 
    "<br />";
        echo 
    $timein;
        }
    ?>
    when I run the file I get this

    Notice: Undefined variable: time in C:\wamp\www\Dome\billableMinutes.php on line 28
    21909527
    2011-08-28 17:52:45
    2011-08-28 16:47:20

  10. #10
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    One issue that I can see is that you don't pass the $time variable to your function so that php can't see it. Try adding $time to billableMinutes as I did below:


    PHP Code:
    function billableMinutes$timein$time){ 
        
    $to_time=strtotime("$time"); //Time now 
        
    $from_time=strtotime($timein); 
        
    $diff=round(abs($to_time $from_time) / 60); 
        return 
    $diff
        } 

  11. #11
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks kreut that fixed that problem pretty quick and it seems to work fine.

    CUPS or kreut what if I wanted it to display hours and minutes if its over 60 minutes say the "time_in" is
    2011-08-28 19:20:11 (from database) and the current time is 2011-08-28 20:29:56 (from current submission) instead of showing 69 minutes have it show 1 hour and 9 minutes. Would that be a different function or work it in to this one?

    when I try this
    PHP Code:
    $hours billableMinutes ($timein$time) / 60;
    echo 
    $hours
    I get this 1.25

    In most cases I will not need to display it as hours and minutes but it would be nice If it did when the time is over an hour.

  12. #12
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I wouldn't be surprised if there's a quicker way to do it, but the following works. You can keep this as part of your function if you like OR outside of the function after you return $diff:

    PHP Code:
    if ($diff>60) { //check to see that we have at least one hour
              
    $num_hours floor($diff/60); //see how many times 60 divides into it then get rid of the decimal (3.2 becomes 3, 4.8 becomes 4)
              
    $num_minutes $diff 60//Now use the modulus function to find the remainder (something from math class!)
              
    echo $num_hours." hours and ".$num_minutes." minutes"//print it out
          
    } else { //in this case we had less than 1 hour
              
    echo $diff." minutes";
          } 
    Hope this helps....

  13. #13
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    Uhm... you're already looping through them -- make a variable called $grandTotal before the while, add to it while looping, output it at the end... simple... a lot simpler than what i'm seeing from everyone else.

    Though some advice since you're just starting out? STOP using echo on EVERY line, STOP putting everything in double quotes, and any values that are the SAME every time you loop should NOT be inside the loop... Also, some proper formatting/indentation could really make your code a hell of a lot easier to read. Likewise some slightly more verbose name would let you axe many of your comments.

    Also, I think your logic for adding up the overcharge is all wrong... I'd probably also CEIL all time estimates instead of round -- but I'm an ass.

    I'm also unclear what you mean by a grand total -- do you mean for the whole timecard, or for ALL timecards output by the while? I'll code up both here.

    Code:
    $rates=array(
    	'adult' => array(
    		'minimumFee' => 12.00, // $
    		'overCharge' =>  0.40, // $ per minute
    		'timeLimit'  => 30     // minutes
    	),
    	'child' => array(
    		'minimumFee' =>  9.00, // $
    		'overCharge' =>  0.30, // $ per minute
    		'timeLimit'  => 30     // minutes
    	),
    	'freeTime' => 6 // minutes
    );
    
    function calcPayment($billableTime,$type) {
    global $rates;
    	$overTime=$billableTime-$rates[$type]['timeLimit'];
    	return (
    		$rates[$type]['minimumFee']+(
    			$overTime>$rates[$type]['timeLimit'] ?
    			$overTime*$rates[$type]['overCharge'] :
    			0
    		)
    	);
    }
    
    $grandTotal=0;
    
    while ($row=mysql_fetch_array($result)) {
    
    	$toTime=strtotime($time); 
    	$fromTime=strtotime($row['time_in']);
    	$totalTime=ceil(abs($toTime-$fromTime)/60); 
    	
    	$billableTime=$totalTime-$rates['freeTime'];
    	$adultPay=calcPayment($billableTime,'adult')*$row['adults'];
    	$childPay=calcPayment($billableTime,'child')*$row['kids'];
    	$grandTotal+=$adultPay+$childPay;
    
    	echo '
    		Timecard for: <b>',$row['name'],'</b><br />
    		Clocked in at:',$row['time_in'],'<br />
    		Current time: ',$time,'<br />
    		Total time: ',$totalTime,' minutes<br />
    		Total for adults: $',$adultPay,'
    		<em>* including 6 <b>FREE</b> minutes</em><br />
    		Total for children: $',$childPay,'"; 
    		<em>* including 6 <b>FREE</b> minutes</em><br />
    		<br />
    		Timecard Total: $',$adultPay+$childPay,'<br />
    		<hr />';
    		
    } // while rows
    
    echo '
    	Grand Total for all Timecards:',$grandTotal,'<br />';
    Assuming I'm reading your original code properly.

    There's an article I always point new programmers at that I really think might help you keep your code cleaner:
    Six ways to write more comprehensible code

    It's meant for C programmers, but PHP is just C in drag with dollar signs in front of it... It talks about how clear names can mean clearer code and easier content and less comments.

    I'd consider moving the static values into defines -- OR maybe leaving them as variables and pulling them from a database -- which is why I changed them into an array.

    Oh, and your original wasn't actually reporting PER child, you were reporting the total for ALL children.

  14. #14
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks deathshadow60 that seems to work fins aswell and thinks for the link. I do see one problem it is not adding the overtime charge this is my current test page

    PHP Code:
     <?php
     
     
    // Connects to SQL and database 

    include 'includes/dbconfig.php';
     
     
     
    date_default_timezone_set ("America/Denver");
    $time date"Y-m-d H:i:s"time());


     
    // now retrives db entry
    date_default_timezone_set ("America/Denver"); $time date"Y-m-d H:i:s"time());
     
         
    $result mysql_query("SELECT * FROM log
    WHERE name LIKE 'Zach' and pin LIKE '1234'"
    );
     

    $rates=array(
        
    'adult' => array(
            
    'minimumFee' => 12.00// $
            
    'overCharge' =>  0.40// $ per minute
            
    'timeLimit'  => 30     // minutes
        
    ),
        
    'child' => array(
            
    'minimumFee' =>  9.00// $
            
    'overCharge' =>  0.30// $ per minute
            
    'timeLimit'  => 30     // minutes
        
    ),
        
    'freeTime' => // minutes
    );

    function 
    calcPayment($billableTime,$type) {
    global 
    $rates;
        
    $overTime=$billableTime-$rates[$type]['timeLimit'];
        return (
            
    $rates[$type]['minimumFee']+(
                
    $overTime>$rates[$type]['timeLimit'] ?
                
    $overTime*$rates[$type]['overCharge'] :
                
    0
            
    )
        );
    }

    $grandTotal=0;

    while (
    $row=mysql_fetch_array($result)) {

        
    $toTime=strtotime($time); 
        
    $fromTime=strtotime($row['time_in']);
        
    $totalTime=ceil(abs($toTime-$fromTime)/60 -6); 
        
        
    $billableTime=$totalTime-$rates['freeTime'];
        
    $adultPay=calcPayment($billableTime,'adult')*$row['adults'];
        
    $childPay=calcPayment($billableTime,'child')*$row['kids'];
        
    $grandTotal+=$adultPay+$childPay;

        echo 
    '
            Timecard for: <b>'
    ,$row['name'],'</b><br />
            Clocked in at:'
    ,$row['time_in'],'<br />
            Current time: '
    ,$time,'<br />
            Total time: '
    ,$totalTime,' minutes<br />
            Total for adults: $'
    ,$adultPay,'
            <em>* including 6 <b>FREE</b> minutes</em><br />
            Total for children: $'
    ,$childPay,
            <em>* including 6 <b>FREE</b> minutes</em><br />
            <br />
            Timecard Total: $'
    ,$adultPay+$childPay,'<br />
            <hr />'
    ;
            
    // while rows

    ?>
    it outputs this

    Timecard for: Zach
    Clocked in at:2011-08-28 21:45:56
    Current time: 2011-08-28 22:41:03
    Total time: 50 minutes
    Total for adults: $12 * including 6 FREE minutes
    Total for children: $9 * including 6 FREE minutes

    Timecard Total: $21

    it should have this

    Timecard for: Zach
    Clocked in at:2011-08-28 21:45:56
    Current time: 2011-08-28 22:41:03
    Total time: 50 minutes
    Total for adults: $17.60 * including 6 FREE minutes
    Total for children: $13.20 * including 6 FREE minutes

    Timecard Total: $30.80

    What is not working properly?

  15. #15
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I found what it is doing but not sure how to fix it. It is not adding any overtime charges until the time gets over 67 min. Then it's adding the extra 40cents to total starting from minute 37(which is correct). I don't see how to fix it.

  16. #16
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    My bad, was basing my code too much on your original. The issue is here:

    Code:
    function calcPayment($billableTime,$type) { 
    global $rates; 
        $overTime=$billableTime-$rates[$type]['timeLimit']; 
        return ( 
            $rates[$type]['minimumFee']+( 
                $overTime>$rates[$type]['timeLimit'] ? 
                $overTime*$rates[$type]['overCharge'] : 
                0 
            ) 
        ); 
    }
    Should read:

    Code:
    function calcPayment($billableTime,$type) { 
    global $rates; 
        $overTime=$billableTime-$rates[$type]['timeLimit']; 
        return ( 
            $rates[$type]['minimumFee']+( 
                $overTime>0 ? 
                $overTime*$rates[$type]['overCharge'] : 
                0 
            ) 
        ); 
    }
    Side note -- why are you subtracting the six here?

    $totalTime=ceil(abs($toTime-$fromTime)/60 -6);

    when the line after does the same thing?

  17. #17
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks again deathshadow60, charlestonolaes, CUPS and kreut!!

    Can you guys suggest good books, practice scripts ect. to learn from. I learn best by implementing what ever it is I'm trying to learn. Like I did with this script, I now have a better idea of organization, functions, and arrays. Any advice will be greatly appreciated.

  18. #18
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I began my PHP adventure in February so take my advice with a grain of salt.

    With that said, I used PHP 6 and MySql5 by Larry Ullman, in addition to David Powers' Training From the Source. Both were super helpful with the one caveat that the Powers book uses the Zend Framework for much of the discussion towards the end of the book. Basically, the framework makes programming a lot easier (at least I think so!), but I feel that if I would have kept myself a bit more "old school" for longer, then I would have developed a much more solid foundation from the start.

    Online, I've also used phpfreaks.com which is a coding forum. For the most part, pretty good, but sometimes, a bit "short" in their answers. Finally, hands down, this forum is THE BEST! All of my php questions were answered with clarity, patience, and an obvious desire to get me to "learn how to fish" instead of just "giving me a fish".

    I'm sure that some of the moderators will give you other helpful PHP titles as well.

    -Eric

  19. #19
    SitePoint Zealot
    Join Date
    Feb 2011
    Location
    Colorado, USA
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the advice Eric..

    I have one more question with this script I want it to give an error if some one tries to clock out with a name that is not in the database or if the PIN they enter is wrong. Before I tried to do this it would not notify if the name and pin did not match a record in the db. And after inserting what I though would fix it is still not notifying the user the name and or PIN is wrong. This is my attempt at making this work.
    PHP Code:
    <?php 
     
    // Connects to your Database 

    include 'includes/dbconfig.php'


     
    //This code runs if the form has been submitted

     
    if (isset($_POST['submit'])) { 



     
    //This makes sure they did not leave any fields blank

     
    if (!$_POST['name'] | !$_POST['pin']  ) {

             die(
    'You did not complete all of the required fields. <a href="javascript:history.go(-1)">Go Back</a>');

         }


     
    // now retrives db entry
    date_default_timezone_set ("America/Denver"); $time date"Y-m-d H:i:s"time());
     
    $name $_POST['name'];
     
    $pin $_POST['pin'];

    //if the name does not exists gives error
     
      
    $usercheck $_POST['name'];

     
    $check mysql_query("SELECT name FROM log WHERE name = '$usercheck'"

    or die(
    mysql_error());

     
    $check2 mysql_num_rows($check);


     if (
    $check2 0) {

             die(
    'Sorry, "'.$_POST['name'].'" is not in the system please <a href="javascript:history.go(-1)">Go Back</a> and try again.');

                     }
     
    else {
         
    $result mysql_query("SELECT * FROM log
    WHERE name LIKE '
    $name' and pin LIKE '$pin'");
     

    $rates=array(
        
    'adult' => array(
            
    'minimumFee' => 12.00// $
            
    'overCharge' =>  0.40// $ per minute
            
    'timeLimit'  => 30     // minutes
        
    ),
        
    'child' => array(
            
    'minimumFee' =>  9.00// $
            
    'overCharge' =>  0.30// $ per minute
            
    'timeLimit'  => 30     // minutes
        
    ),
        
    'freeTime' => // minutes
    );

    function 
    calcPayment($billableTime,$type) { 
    global 
    $rates
        
    $overTime=$billableTime-$rates[$type]['timeLimit']; 
        return ( 
            
    $rates[$type]['minimumFee']+( 
                
    $overTime>
                
    $overTime*$rates[$type]['overCharge'] : 
                

            

        ); 
    }

    $grandTotal=0;

    while (
    $row=mysql_fetch_array($result)) {

        
    $toTime=strtotime($time); 
        
    $fromTime=strtotime($row['time_in']);
        
    $totalTime=ceil(abs($toTime-$fromTime)/60); 
        
        
    $billableTime=$totalTime-$rates['freeTime'];
        
    $adultPay=calcPayment($billableTime,'adult')*$row['adults'];
        
    $childPay=calcPayment($billableTime,'child')*$row['kids'];
        
    $grandTotal+=$adultPay+$childPay;
        
    $adultindividual=$adultPay/$row['adults'];
        
    $childindividual=$childPay/$row['kids'];
        echo 
    '
            Timecard for: <b>'
    ,$row['name'],'</b><br />
            Clocked in at:'
    ,$row['time_in'],'<br />
            Current time: '
    ,$time,'<br />
            Total time: '
    ,$totalTime,' minutes<br />
            Adults: $ '
    ,$adultindividual,' per adult * ',$row['adults'],' = $',$adultPay,'<br />
            Children: $ '
    ,$childindividual,' per child * ',$row['kids'],' = $',$childPay,'<br /> 
            <br />
            Timecard Total: $'
    ,$adultPay+$childPay,'<br />
            <hr />'
    ;
            
            
    }} 
    // while rows

    $timein $row['time_in'];

        
        
      
    mysql_query("DELETE FROM log WHERE name LIKE '$name' and pin LIKE '$pin'");
    ?>
     
     <?php 
     


     else 
     {
     
    ?>
    <table cellpadding="10">
        <tr>
            <td width="450">
                Thanks again for chossing <u><i>Tanglewood Golf Dome</i></u> to improve your golf game. To clock out please enter your sign in name and PIN. Time and rate will be calculated and return
                total time spent in dome and the cost of your practice.
            </td>
            <td>
                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

                <table border="0">
                    <tr>
                        <td>
                            Name: 
                        </td>
                        <td>
                            <input type="text" name="name" maxlength="60">
                        </td>    
                    </tr>
                    <tr>    
                        <td align="right">
                            PIN:
                        </td>
                        <td>
                            <input type="password" name="pin" maxlength="10">
                        </td>
                    </tr>
                    <tr>
                        <th colspan=2>
                            <input type="submit" name="submit" value="Clock Out">
                        </th>
                    </tr>
                </table>
                </form>
            </td>
        <tr>
    </table>    

     <?php

     
    }
     
    ?>

  20. #20
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    PHP Code:
    if (!$_POST['name'] | !$_POST['pin']  ) { 
    Should be double IBar || not single.

    That could be a slightly more rigorous check.
    PHP Code:
    if( 
    empty(
    trim($_POST['name'])) || empty(trim($_POST['pin'])) 
    ){ 
    // ... 

  21. #21
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Cups View Post
    That could be a slightly more rigorous check.
    PHP Code:
    if( 
    empty(
    trim($_POST['name'])) || empty(trim($_POST['pin'])) 
    ){ 
    // ... 
    Which could still be filling up the error log since empty on an unset index still files a silent error... which is why isset should be called first.

  22. #22
    SitePoint Wizard bronze trophy Immerse's Avatar
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    1,661
    Mentioned
    7 Post(s)
    Tagged
    1 Thread(s)
    Empty will in fact allow undefined variables or undefined indexes, and return true (i.e. it's empty as it doesn't exist).

    Very handy!

  23. #23
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Immerse View Post
    Empty will in fact allow undefined variables or undefined indexes, and return true (i.e. it's empty as it doesn't exist).

    Very handy!
    Check your php.log

  24. #24
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    I thought isset() was already being called on those vars - but it was checking the 'submit' var.

    By the way, I thought checking for the existence of a submit button click was an unreliable test of the form being submitted because if the user fills in your form and presses 'Enter' the value of the submit button is not transmitted on all browsers (IE?).

    Yes, of course without checking isset will be filling up your logfiles - but you really should be running on display_errors = on in a dev environment so that you see these things as you work.

    So yes, check if the name is set, then trim it, then see if it is empty if you want.

    Which really begs the question, if you are going to do that check then you might as well filter against what you will be claiming will be an acceptable name. If a is acceptable then, yes, trim/empty is a good enough check.

    PHP Code:
    if( 
    (isset(
    $_POST['name'] && !empty(trim($_POST['name'])) )
    &&  
    ( isset(
    $_POST['email'] && !empty(trim($_POST['email'])) )
    ){
    // now you can say your two form elements have been 
    // submitted and that they both have something inside them
    // which is more than a space - but could still be something nasty



    instead of if (isset($_POST['submit']));

    In practice though, many of us use JS to simply not permit the user to submit the form at all if certain minimum conditions have not been met. (not empty, name longer than 3 chars, email at least contains an @).

    This is a usability win on the onehand - but given the nature of the web, this is of course dead easy to subvert (turn JS off, for example).

    The JS checking has absolutely nothing to do with security.

  25. #25
    SitePoint Enthusiast
    Join Date
    Sep 2009
    Posts
    53
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Also isset($_POST['submit']) is bad anyway because an IE problem with isset submit.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •