IF statement screwing up

Discussion in 'PHP' started by lmyrick, Jan 8, 2007.

  1. #1
    I'm using the following code when entering data into a mysql database:

    if ($regular == "no") { $hours = 0.00; }
    $query = "INSERT INTO records VALUES('', '$user_id', '$regular', CURDATE(), '$day_of_week', '$month', '$year', '$hours', '$note', $nonreg_hours)";

    Now if the $regular variable (sent via post) is 'no', the code works fine and the record is inserted into the db. HOWEVER, if $regular = 'yes', the insert query doesn't work. What am I doing wrong here?
     
    lmyrick, Jan 8, 2007 IP
  2. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #2
    Try this instead:

    
    if ($_POST['regular'] == "no") { $hours = 0.00; }
    
    PHP:
    Peace,
     
    Barti1987, Jan 8, 2007 IP
  3. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #3
    Your SQL query is wrong, here's my recommendation:

    
    
    $regular = $_POST['regular'];
    
    IF( $regular == "no" ){
    
    $curdate = CURDATE();
    
    $hours = 0.00;
    
    $query = mysql_query("INSERT INTO `records` (`user_id`, `regular`, `date`, `day_of_week`, `month`, `year`, `hours`, `note`, `nonreg_hours`) VALUES('$user_id', '$regular', '$curdate', '$day_of_week', '$month', '$year', '$hours', '$note', '$nonreg_hours')");
    
    }ELSEIF( $regular == "yes" ){
    
    // Type here what happens if it's "yes"
    
    }
    
    
    PHP:
     
    BRUm, Jan 8, 2007 IP
  4. rodney88

    rodney88 Guest

    Messages:
    480
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Presumably the problem is because when $regular == 'yes', $hours is never set.

    Try
    $hours = ( $regular == 'no' ) ? 0.00 : '';
    PHP:
    (or replace the last '' with what $hours should equal when $regular is not no)

    instead of
    if ($regular == "no") { $hours = 0.00; }
     
    rodney88, Jan 8, 2007 IP
  5. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #5
    He also has some syntax wrong.
     
    BRUm, Jan 9, 2007 IP
  6. rodney88

    rodney88 Guest

    Messages:
    480
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #6
    The syntax is fine. CURDATE() is a mySQL function, not a PHP function - your code will just give fatal error function not defined.

    The query could be improved (as you did) but that's just a best practice, not wrong.
     
    rodney88, Jan 9, 2007 IP